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:

{% tabs %} {% tab title=”Go” %}

  1. nc, err := nats.Connect("demo.nats.io")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. ec, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. defer ec.Close()
  11. // Define the object
  12. type stock struct {
  13. Symbol string
  14. Price int
  15. }
  16. // Publish the message
  17. if err := ec.Publish("updates", &stock{Symbol: "GOOG", Price: 1200}); err != nil {
  18. log.Fatal(err)
  19. }

{% endtab %}

{% tab title=”Java” %}

  1. class StockForJsonPub {
  2. public String symbol;
  3. public float price;
  4. }
  5. public class PublishJSON {
  6. public static void main(String[] args) {
  7. try {
  8. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  9. // Create the data object
  10. StockForJsonPub stk = new StockForJsonPub();
  11. stk.symbol="GOOG";
  12. stk.price=1200;
  13. // use Gson to encode the object to JSON
  14. GsonBuilder builder = new GsonBuilder();
  15. Gson gson = builder.create();
  16. String json = gson.toJson(stk);
  17. // Publish the message
  18. nc.publish("updates", json.getBytes(StandardCharsets.UTF_8));
  19. // Make sure the message goes through before we close
  20. nc.flush(Duration.ZERO);
  21. nc.close();
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }

{% endtab %}

{% tab title=”JavaScript” %}

  1. const jc = JSONCodec();
  2. nc.publish("updates", jc.encode({ ticker: "GOOG", price: 2868.87 }));

{% endtab %}

{% tab title=”Python” %}

  1. nc = NATS()
  2. await nc.connect(servers=["nats://demo.nats.io:4222"])
  3. await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())

{% endtab %}

{% tab title=”Ruby” %}

  1. require 'nats/client'
  2. require 'json'
  3. NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
  4. nc.publish("updates", {"symbol": "GOOG", "price": 1200}.to_json)
  5. end

{% endtab %}

{% tab title=”C” %}

  1. // Structured data is not configurable in C NATS Client.

{% endtab %} {% endtabs %}