Powered By GitBook
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
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
// Subscribe
8
sub, err := nc.SubscribeSync("updates")
9
if err != nil {
10
log.Fatal(err)
11
}
12
13
// Wait for a message
14
msg, err := sub.NextMsg(10 * time.Second)
15
if err != nil {
16
log.Fatal(err)
17
}
18
19
// Use the response
20
log.Printf("Reply: %s", msg.Data)
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
// Subscribe
4
Subscription sub = nc.subscribe("updates");
5
6
// Read a message
7
Message msg = sub.nextMessage(Duration.ZERO);
8
9
String str = new String(msg.getData(), StandardCharsets.UTF_8);
10
System.out.println(str);
11
12
// Close the connection
13
nc.close();
Copied!
1
// node-nats subscriptions are always async.
Copied!
1
# Asyncio NATS client currently does not have a sync subscribe API
Copied!
1
# The Ruby NATS client subscriptions are all async.
Copied!
1
/ Typescript NATS subscriptions are always async.
Copied!
1
natsConnection *conn = NULL;
2
natsSubscription *sub = NULL;
3
natsMsg *msg = NULL;
4
natsStatus s = NATS_OK;
5
6
s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
7
8
// Subscribe
9
if (s == NATS_OK)
10
s = natsConnection_SubscribeSync(&sub, conn, "updates");
11
12
// Wait for messages
13
if (s == NATS_OK)
14
s = natsSubscription_NextMsg(&msg, sub, 10000);
15
16
if (s == NATS_OK)
17
{
18
printf("Received msg: %s - %.*s\n",
19
natsMsg_GetSubject(msg),
20
natsMsg_GetDataLength(msg),
21
natsMsg_GetData(msg));
22
23
// Destroy message that was received
24
natsMsg_Destroy(msg);
25
}
26
27
(...)
28
29
// Destroy objects that were created
30
natsSubscription_Destroy(sub);
31
natsConnection_Destroy(conn);
Copied!
Last modified 1yr ago
Export as PDF
Copy link