Powered By GitBook
Unsubscribing After N Messages
NATS provides a special form of unsubscribe that is configured with a message count and takes effect when that many messages are sent to a subscriber. This mechanism is very useful if only a single message is expected.
The message count you provide is the total message count for a subscriber. So if you unsubscribe with a count of 1, the server will stop sending messages to that subscription after it has received one message. If the subscriber has already received one or more messages, the unsubscribe will be immediate. This action based on history can be confusing if you try to auto-unsubscribe on a long running subscription, but is logical for a new one.
Auto-unsubscribe is based on the total messages sent to a subscriber, not just the new ones. Most of the client libraries also track the max message count after an auto-unsubscribe request. On reconnect, this enables clients to resend the unsubscribe with an updated total.
The following example shows unsubscribe after a single message:
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
// Sync Subscription
8
sub, err := nc.SubscribeSync("updates")
9
if err != nil {
10
log.Fatal(err)
11
}
12
if err := sub.AutoUnsubscribe(1); err != nil {
13
log.Fatal(err)
14
}
15
16
// Async Subscription
17
sub, err = nc.Subscribe("updates", func(_ *nats.Msg) {})
18
if err != nil {
19
log.Fatal(err)
20
}
21
if err := sub.AutoUnsubscribe(1); err != nil {
22
log.Fatal(err)
23
}
Copied!
1
Connection nc = Nats.connect("nats://demo.nats.io:4222");
2
Dispatcher d = nc.createDispatcher((msg) -> {
3
String str = new String(msg.getData(), StandardCharsets.UTF_8);
4
System.out.println(str);
5
});
6
7
// Sync Subscription
8
Subscription sub = nc.subscribe("updates");
9
sub.unsubscribe(1);
10
11
// Async Subscription
12
d.subscribe("updates");
13
d.unsubscribe("updates", 1);
14
15
// Close the connection
16
nc.close();
Copied!
1
let nc = NATS.connect({
2
url: "nats://demo.nats.io:4222"
3
});
4
// `max` specifies the number of messages that the server will forward
5
// The server will auto-cancel.
6
let opts = {max: 10};
7
let sub = nc.subscribe(NATS.createInbox(), opts, (msg) => {
8
t.log(msg);
9
});
10
11
// another way after 10 messages
12
let sub2 = nc.subscribe(NATS.createInbox(), (err, msg) => {
13
t.log(msg.data);
14
});
15
// if the subscription already received 10 messages, the handler
16
// won't get any more messages
17
nc.unsubscribe(sub2, 10);
Copied!
1
nc = NATS()
2
3
await nc.connect(servers=["nats://demo.nats.io:4222"])
4
5
async def cb(msg):
6
print(msg)
7
8
sid = await nc.subscribe("updates", cb=cb)
9
await nc.auto_unsubscribe(sid, 1)
10
await nc.publish("updates", b'All is Well')
11
12
# Won't be received...
13
await nc.publish("updates", b'...')
Copied!
1
require 'nats/client'
2
require 'fiber'
3
4
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
5
Fiber.new do
6
f = Fiber.current
7
8
nc.subscribe("time", max: 1) do |msg, reply|
9
f.resume Time.now
10
end
11
12
nc.publish("time", 'What is the time?', NATS.create_inbox)
13
14
# Use the response
15
msg = Fiber.yield
16
puts "Reply: #{msg}"
17
18
# Won't be received
19
nc.publish("time", 'What is the time?', NATS.create_inbox)
20
21
end.resume
22
end
Copied!
1
// `max` specifies the number of messages that the server will forward
2
// The server will auto-cancel
3
let opts = {max: 10};
4
let sub = await nc.subscribe(createInbox(), (err, msg) => {
5
t.log(msg.data);
6
}, opts);
7
8
// another way after 10 messages
9
let sub2 = await nc.subscribe(createInbox(), (err, msg) => {
10
t.log(msg.data);
11
});
12
// if the subscription already received 10 messages, the handler
13
// won't get any more messages
14
sub2.unsubscribe(10);
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
// Unsubscribe after 1 message is received
13
if (s == NATS_OK)
14
s = natsSubscription_AutoUnsubscribe(sub, 1);
15
16
// Wait for messages
17
if (s == NATS_OK)
18
s = natsSubscription_NextMsg(&msg, sub, 10000);
19
20
if (s == NATS_OK)
21
{
22
printf("Received msg: %s - %.*s\n",
23
natsMsg_GetSubject(msg),
24
natsMsg_GetDataLength(msg),
25
natsMsg_GetData(msg));
26
27
// Destroy message that was received
28
natsMsg_Destroy(msg);
29
}
30
31
(...)
32
33
// Destroy objects that were created
34
natsSubscription_Destroy(sub);
35
natsConnection_Destroy(conn);
Copied!
Last modified 1yr ago
Export as PDF
Copy link