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

  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. // Define the object
  19. type stock struct {
  20. Symbol string
  21. Price int
  22. }
  23. wg := sync.WaitGroup{}
  24. wg.Add(1)
  25. // Subscribe
  26. // Decoding errors will be passed to the function supplied via
  27. // nats.ErrorHandler above, and the callback supplied here will
  28. // not be invoked.
  29. if _, err := ec.Subscribe("updates", func(s *stock) {
  30. log.Printf("Stock: %s - Price: %v", s.Symbol, s.Price)
  31. wg.Done()
  32. }); err != nil {
  33. log.Fatal(err)
  34. }
  35. // Wait for a message to come in
  36. wg.Wait()

Java

  1. class StockForJsonSub {
  2. public String symbol;
  3. public float price;
  4. public String toString() {
  5. return symbol + " is at " + price;
  6. }
  7. }
  8. public class SubscribeJSON {
  9. public static void main(String[] args) {
  10. try {
  11. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  12. // Use a latch to wait for 10 messages to arrive
  13. CountDownLatch latch = new CountDownLatch(10);
  14. // Create a dispatcher and inline message handler
  15. Dispatcher d = nc.createDispatcher((msg) -> {
  16. Gson gson = new Gson();
  17. String json = new String(msg.getData(), StandardCharsets.UTF_8);
  18. StockForJsonSub stk = gson.fromJson(json, StockForJsonSub.class);
  19. // Use the object
  20. System.out.println(stk);
  21. latch.countDown();
  22. });
  23. // Subscribe
  24. d.subscribe("updates");
  25. // Wait for a message to come in
  26. latch.await();
  27. // Close the connection
  28. nc.close();
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }

JavaScript

  1. let nc = NATS.connect({
  2. url: "nats://demo.nats.io:4222",
  3. json: true
  4. });
  5. nc.subscribe('updates', (msg) => {
  6. if(msg && msg.ticker === 'TSLA') {
  7. t.log('got message:', msg);
  8. }
  9. });

Python

  1. import asyncio
  2. import json
  3. from nats.aio.client import Client as NATS
  4. from nats.aio.errors import ErrTimeout
  5. async def run(loop):
  6. nc = NATS()
  7. await nc.connect(servers=["nats://127.0.0.1:4222"], loop=loop)
  8. async def message_handler(msg):
  9. data = json.loads(msg.data.decode())
  10. print(data)
  11. sid = await nc.subscribe("updates", cb=message_handler)
  12. await nc.flush()
  13. await nc.auto_unsubscribe(sid, 2)
  14. await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode())
  15. await asyncio.sleep(1, loop=loop)
  16. await nc.close()

Ruby

  1. require 'nats/client'
  2. require 'json'
  3. NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
  4. nc.subscribe("updates") do |msg|
  5. m = JSON.parse(msg)
  6. # {"symbol"=>"GOOG", "price"=>12}
  7. p m
  8. end
  9. end

TypeScript

  1. let nc = await connect({
  2. url: "nats://demo.nats.io:4222",
  3. payload: Payload.JSON
  4. });
  5. nc.subscribe('updates', (err, msg) => {
  6. t.log('got message:', msg.data ? msg.data : "no payload");
  7. });

C

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