Powered By GitBook
Sending Structured Data
Some client libraries provide helpers to send structured data while others depend on the application to perform any encoding and decoding and just take byte arrays for sending. The following example shows how to send JSON but this could easily be altered to send a protocol buffer, YAML or some other format. JSON is a text format so we also have to encode the string in most languages to bytes. We are using UTF-8, the JSON standard encoding.
Take a simple stock ticker that sends the symbol and price of each stock:
Go
Java
JavaScript
Python
Ruby
TypeScript
C
1
nc, err := nats.Connect("demo.nats.io")
2
if err != nil {
3
log.Fatal(err)
4
}
5
defer nc.Close()
6
7
ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
8
if err != nil {
9
log.Fatal(err)
10
}
11
defer ec.Close()
12
13
// Define the object
14
type stock struct {
15
Symbol string
16
Price int
17
}
18
19
// Publish the message
20
if err := ec.Publish("updates", &stock{Symbol: "GOOG", Price: 1200}); err != nil {
21
log.Fatal(err)
22
}
Copied!
1
class StockForJsonPub {
2
public String symbol;
3
public float price;
4
}
5
6
public class PublishJSON {
7
public static void main(String[] args) {
8
try {
9
Connection nc = Nats.connect("nats://demo.nats.io:4222");
10
11
// Create the data object
12
StockForJsonPub stk = new StockForJsonPub();
13
stk.symbol="GOOG";
14
stk.price=1200;
15
16
// use Gson to encode the object to JSON
17
GsonBuilder builder = new GsonBuilder();
18
Gson gson = builder.create();
19
String json = gson.toJson(stk);
20
21
// Publish the message
22
nc.publish("updates", json.getBytes(StandardCharsets.UTF_8));
23
24
// Make sure the message goes through before we close
25
nc.flush(Duration.ZERO);
26
nc.close();
27
} catch (Exception e) {
28
e.printStackTrace();
29
}
30
}
31
}
Copied!
1
let nc = NATS.connect({url: "nats://demo.nats.io:4222", json: true});
2
nc.publish('updates', {ticker: 'GOOG', price: 1200});
Copied!
1
nc = NATS()
2
3
await nc.connect(servers=["nats://demo.nats.io:4222"])
4
5
await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())
Copied!
1
require 'nats/client'
2
require 'json'
3
4
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
5
nc.publish("updates", {"symbol": "GOOG", "price": 1200}.to_json)
6
end
Copied!
1
let nc = await connect({
2
url: "nats://demo.nats.io:4222",
3
payload: Payload.JSON
4
});
5
6
nc.publish('updates', {ticker: 'GOOG', price: 1200});
Copied!
1
// Structured data is not configurable in C NATS Client.
Copied!
Last modified 1yr ago
Export as PDF
Copy link