Powered By GitBook
Structured Data
Client libraries may provide tools to help receive structured data, like JSON. The core traffic to the NATS server will always be opaque byte arrays. The server does not process message payloads in any form. For libraries that don't provide helpers, you can always encode and decode data before sending the associated bytes to the NATS client.
For example, to receive JSON you could do:
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
nc, err := nats.Connect("demo.nats.io",
2
nats.ErrorHandler(func(nc *nats.Conn, s *nats.Subscription, err error) {
3
if s != nil {
4
log.Printf("Async error in %q/%q: %v", s.Subject, s.Queue, err)
5
} else {
6
log.Printf("Async error outside subscription: %v", err)
7
}
8
}))
9
if err != nil {
10
log.Fatal(err)
11
}
12
defer nc.Close()
13
ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
14
if err != nil {
15
log.Fatal(err)
16
}
17
defer ec.Close()
18
19
// Define the object
20
type stock struct {
21
Symbol string
22
Price int
23
}
24
25
wg := sync.WaitGroup{}
26
wg.Add(1)
27
28
// Subscribe
29
// Decoding errors will be passed to the function supplied via
30
// nats.ErrorHandler above, and the callback supplied here will
31
// not be invoked.
32
if _, err := ec.Subscribe("updates", func(s *stock) {
33
log.Printf("Stock: %s - Price: %v", s.Symbol, s.Price)
34
wg.Done()
35
}); err != nil {
36
log.Fatal(err)
37
}
38
39
// Wait for a message to come in
40
wg.Wait()
Copied!
1
class StockForJsonSub {
2
public String symbol;
3
public float price;
4
5
public String toString() {
6
return symbol + " is at " + price;
7
}
8
}
9
10
public class SubscribeJSON {
11
public static void main(String[] args) {
12
13
try {
14
Connection nc = Nats.connect("nats://demo.nats.io:4222");
15
16
// Use a latch to wait for 10 messages to arrive
17
CountDownLatch latch = new CountDownLatch(10);
18
19
// Create a dispatcher and inline message handler
20
Dispatcher d = nc.createDispatcher((msg) -> {
21
Gson gson = new Gson();
22
23
String json = new String(msg.getData(), StandardCharsets.UTF_8);
24
StockForJsonSub stk = gson.fromJson(json, StockForJsonSub.class);
25
26
// Use the object
27
System.out.println(stk);
28
29
latch.countDown();
30
});
31
32
// Subscribe
33
d.subscribe("updates");
34
35
// Wait for a message to come in
36
latch.await();
37
38
// Close the connection
39
nc.close();
40
} catch (Exception e) {
41
e.printStackTrace();
42
}
43
}
44
}
Copied!
1
let nc = NATS.connect({
2
url: "nats://demo.nats.io:4222",
3
json: true
4
});
5
6
nc.subscribe('updates', (msg) => {
7
if(msg && msg.ticker === 'TSLA') {
8
t.log('got message:', msg);
9
}
10
});
Copied!
1
import asyncio
2
import json
3
from nats.aio.client import Client as NATS
4
from nats.aio.errors import ErrTimeout
5
6
async def run(loop):
7
nc = NATS()
8
9
await nc.connect(servers=["nats://127.0.0.1:4222"], loop=loop)
10
11
async def message_handler(msg):
12
data = json.loads(msg.data.decode())
13
print(data)
14
15
sid = await nc.subscribe("updates", cb=message_handler)
16
await nc.flush()
17
18
await nc.auto_unsubscribe(sid, 2)
19
await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())
20
await asyncio.sleep(1, loop=loop)
21
await nc.close()
Copied!
1
require 'nats/client'
2
require 'json'
3
4
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
5
nc.subscribe("updates") do |msg|
6
m = JSON.parse(msg)
7
8
# {"symbol"=>"GOOG", "price"=>12}
9
p m
10
end
11
end
Copied!
1
let nc = await connect({
2
url: "nats://demo.nats.io:4222",
3
payload: Payload.JSON
4
});
5
6
nc.subscribe('updates', (err, msg) => {
7
t.log('got message:', msg.data ? msg.data : "no payload");
8
});
Copied!
1
// Structured data is not configurable in C NATS Client.
Copied!
Last modified 1yr ago
Export as PDF
Copy link