Powered By GitBook
Asynchronous Subscriptions
Asynchronous subscriptions use callbacks of some form to notify an application when a message arrives. These subscriptions are usually easier to work with, but do represent some form of internal work and resource usage, i.e. threads, by the library. Check your library's documentation for any resource usage associated with asynchronous subscriptions.
Note: For a given subscription, messages are dispatched serially, one message at a time. If your application does not care about processing ordering and would prefer the messages to be dispatched concurrently, it is the application's responsibility to move them to some internal queue to be picked up by threads/go routines.
The following example subscribes to the subject updates and handles the incoming messages:
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
// Use a WaitGroup to wait for a message to arrive
8
wg := sync.WaitGroup{}
9
wg.Add(1)
10
11
// Subscribe
12
if _, err := nc.Subscribe("updates", func(m *nats.Msg) {
13
wg.Done()
14
}); err != nil {
15
log.Fatal(err)
16
}
17
18
// Wait for a message to come in
19
wg.Wait()
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
3
// Use a latch to wait for a message to arrive
4
CountDownLatch latch = new CountDownLatch(1);
5
6
// Create a dispatcher and inline message handler
7
Dispatcher d = nc.createDispatcher((msg) -> {
8
String str = new String(msg.getData(), StandardCharsets.UTF_8);
9
System.out.println(str);
10
latch.countDown();
11
});
12
13
// Subscribe
14
d.subscribe("updates");
15
16
// Wait for a message to come in
17
latch.await();
18
19
// Close the connection
20
nc.close();
Copied!
1
let nc = NATS.connect({
2
url: "nats://demo.nats.io:4222"
3
});
4
nc.subscribe("updates", (msg) => {
5
t.log(msg);
6
});
Copied!
1
nc = NATS()
2
3
await nc.connect(servers=["nats://demo.nats.io:4222"])
4
5
future = asyncio.Future()
6
7
async def cb(msg):
8
nonlocal future
9
future.set_result(msg)
10
11
await nc.subscribe("updates", cb=cb)
12
await nc.publish("updates", b'All is Well')
13
await nc.flush()
14
15
# Wait for message to come in
16
msg = await asyncio.wait_for(future, 1)
Copied!
1
require 'nats/client'
2
3
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
4
nc.subscribe("updates") do |msg|
5
puts msg
6
nc.close
7
end
8
9
nc.publish("updates", "All is Well")
10
end
Copied!
1
nc.subscribe("updates", (err, msg) => {
2
if(err) {
3
console.log('error', err);
4
} else {
5
t.log(msg.data);
6
}
7
});
Copied!
1
static void
2
onMsg(natsConnection *conn, natsSubscription *sub, natsMsg *msg, void *closure)
3
{
4
printf("Received msg: %s - %.*s\n",
5
natsMsg_GetSubject(msg),
6
natsMsg_GetDataLength(msg),
7
natsMsg_GetData(msg));
8
9
// Need to destroy the message!
10
natsMsg_Destroy(msg);
11
}
12
13
(...)
14
15
natsConnection *conn = NULL;
16
natsSubscription *sub = NULL;
17
natsStatus s;
18
19
s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
20
if (s == NATS_OK)
21
{
22
// Creates an asynchronous subscription on subject "foo".
23
// When a message is sent on subject "foo", the callback
24
// onMsg() will be invoked by the client library.
25
// You can pass a closure as the last argument.
26
s = natsConnection_Subscribe(&sub, conn, "foo", onMsg, NULL);
27
}
28
29
(...)
30
31
32
// Destroy objects that were created
33
natsSubscription_Destroy(sub);
34
natsConnection_Destroy(conn);
Copied!
Last modified 1yr ago
Export as PDF
Copy link