The client libraries provide a means to unsubscribe a previous subscription request.
This process requires an interaction with the server, so for an asynchronous subscription there may be a small window of time where a message comes through as the unsubscribe is processed by the library. Ignoring that slight edge case, the client library will clean up any outstanding messages and tell the server that the subscription is no longer used.
Connection nc =Nats.connect("nats://demo.nats.io:4222");Dispatcher d =nc.createDispatcher((msg) -> {String str =newString(msg.getData(),StandardCharsets.UTF_8);System.out.println(str);});// Sync SubscriptionSubscription sub =nc.subscribe("updates");sub.unsubscribe();// Async Subscriptiond.subscribe("updates");d.unsubscribe("updates");// Close the connectionnc.close();
constsc=StringCodec();// set up a subscription to process a requestconstsub=nc.subscribe(createInbox(), (_err, m) => {m.respond(sc.encode(newDate().toLocaleTimeString()));});// without arguments the subscription will cancel when the server receives it// you can also specify how many messages are expected by the subscriptionsub.unsubscribe();
nc =NATS()await nc.connect(servers=["nats://demo.nats.io:4222"])future = asyncio.Future()asyncdefcb(msg):nonlocal future future.set_result(msg)sub =await nc.subscribe("updates", cb=cb)await nc.publish("updates", b'All is Well')# Remove interest in subjectawait sub.unsubscribe()# Won't be received...await nc.publish("updates", b'...')
require'nats/client'require'fiber'NATS.start(servers:["nats://127.0.0.1:4222"]) do|nc|Fiber.newdo f =Fiber.current sid = nc.subscribe("time") do|msg, reply| f.resume Time.nowend nc.publish("time",'What is the time?',NATS.create_inbox)# Use the response msg =Fiber.yieldputs"Reply: #{msg}" nc.unsubscribe(sid)# Won't be received nc.publish("time",'What is the time?',NATS.create_inbox)end.resumeend
natsConnection *conn =NULL;natsSubscription *sub =NULL;natsStatus s = NATS_OK;s =natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);// Subscribeif (s == NATS_OK) s =natsConnection_SubscribeSync(&sub, conn,"updates");// Unsubscribeif (s == NATS_OK) s =natsSubscription_Unsubscribe(sub);(...)// Destroy objects that were creatednatsSubscription_Destroy(sub);natsConnection_Destroy(conn);