Synchronous Subscriptions

Synchronous subscriptions require the application to wait for messages. This type of subscription is easy to set-up and use, but requires the application to deal with looping if multiple messages are expected. For situations where a single message is expected, synchronous subscriptions are sometimes easier to manage, depending on the language.

For example, to subscribe to the subject updates and receive a single message you could do:

Go

  1. nc, err := nats.Connect("demo.nats.io")
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. defer nc.Close()
  6. // Subscribe
  7. sub, err := nc.SubscribeSync("updates")
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. // Wait for a message
  12. msg, err := sub.NextMsg(10 * time.Second)
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. // Use the response
  17. log.Printf("Reply: %s", msg.Data)

Java

  1. Connection nc = Nats.connect("nats://demo.nats.io:4222");
  2. // Subscribe
  3. Subscription sub = nc.subscribe("updates");
  4. // Read a message
  5. Message msg = sub.nextMessage(Duration.ZERO);
  6. String str = new String(msg.getData(), StandardCharsets.UTF_8);
  7. System.out.println(str);
  8. // Close the connection
  9. nc.close();

JavaScript

  1. // node-nats subscriptions are always async.

Python

  1. # Asyncio NATS client currently does not have a sync subscribe API

Ruby

  1. # The Ruby NATS client subscriptions are all async.

TypeScript

  1. / Typescript NATS subscriptions are always async.

C

  1. natsConnection *conn = NULL;
  2. natsSubscription *sub = NULL;
  3. natsMsg *msg = NULL;
  4. natsStatus s = NATS_OK;
  5. s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
  6. // Subscribe
  7. if (s == NATS_OK)
  8. s = natsConnection_SubscribeSync(&sub, conn, "updates");
  9. // Wait for messages
  10. if (s == NATS_OK)
  11. s = natsSubscription_NextMsg(&msg, sub, 10000);
  12. if (s == NATS_OK)
  13. {
  14. printf("Received msg: %s - %.*s\n",
  15. natsMsg_GetSubject(msg),
  16. natsMsg_GetDataLength(msg),
  17. natsMsg_GetData(msg));
  18. // Destroy message that was received
  19. natsMsg_Destroy(msg);
  20. }
  21. (...)
  22. // Destroy objects that were created
  23. natsSubscription_Destroy(sub);
  24. natsConnection_Destroy(conn);