Including a Reply Subject
The optional reply-to field when publishing a message can be used on the receiving side to respond. The reply-to subject is often called an inbox, and most libraries may provide a method for generating unique inbox subjects. Most libraries also provide for the request-reply pattern with a single call. For example to send a request to the subject time
, with no content for the messages, you might:
Go
nc, err := nats.Connect("demo.nats.io")
if err != nil {
log.Fatal(err)
}
defer nc.Close()
// Create a unique subject name for replies.
uniqueReplyTo := nats.NewInbox()
// Listen for a single response
sub, err := nc.SubscribeSync(uniqueReplyTo)
if err != nil {
log.Fatal(err)
}
// Send the request.
// If processing is synchronous, use Request() which returns the response message.
if err := nc.PublishRequest("time", uniqueReplyTo, nil); err != nil {
log.Fatal(err)
}
// Read the reply
msg, err := sub.NextMsg(time.Second)
if err != nil {
log.Fatal(err)
}
// Use the response
log.Printf("Reply: %s", msg.Data)
Java
Connection nc = Nats.connect("nats://demo.nats.io:4222");
// Create a unique subject name
String uniqueReplyTo = NUID.nextGlobal();
// Listen for a single response
Subscription sub = nc.subscribe(uniqueReplyTo);
sub.unsubscribe(1);
// Send the request
nc.publish("time", uniqueReplyTo, null);
// Read the reply
Message msg = sub.nextMessage(Duration.ofSeconds(1));
// Use the response
System.out.println(new String(msg.getData(), StandardCharsets.UTF_8));
// Close the connection
nc.close();
JavaScript
let nc = NATS.connect({url: "nats://demo.nats.io:4222"});
// set up a subscription to process the request
nc.subscribe('time', (msg, reply) => {
if(reply) {
nc.publish(reply, new Date().toLocaleTimeString());
}
});
// create a subscription subject that the responding send replies to
let inbox = NATS.createInbox();
nc.subscribe(inbox, {max: 1}, (msg) => {
t.log('the time is', msg);
nc.close();
});
nc.publish('time', "", inbox);
Python
nc = NATS()
future = asyncio.Future()
async def sub(msg):
nonlocal future
future.set_result(msg)
await nc.connect(servers=["nats://demo.nats.io:4222"])
await nc.subscribe("time", cb=sub)
unique_reply_to = new_inbox()
await nc.publish_request("time", unique_reply_to, b'')
# Use the response
msg = await asyncio.wait_for(future, 1)
print("Reply:", msg)
Ruby
require 'nats/client'
require 'fiber'
NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
Fiber.new do
f = Fiber.current
nc.subscribe("time") do |msg, reply|
f.resume msg
end
nc.publish("time", 'example', NATS.create_inbox)
# Use the response
msg = Fiber.yield
puts "Reply: #{msg}"
end.resume
end
TypeScript
// set up a subscription to process the request
await nc.subscribe('time', (err, msg) => {
if (err) {
// this example is running inside of a promise
reject();
return;
}
if (msg.reply) {
nc.publish(msg.reply, new Date().toLocaleTimeString());
}
});
// create a subscription subject that the responding send replies to
let inbox = createInbox();
await nc.subscribe(inbox, (err, msg) => {
t.log('the time is', msg.data);
// this example is running inside of a promise
nc.close();
resolve();
}, {max: 1});
nc.publish('time', "", inbox);
C
natsConnection *conn = NULL;
natsStatus s = NATS_OK;
s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
// Publish a message and provide a reply subject
if (s == NATS_OK)
s = natsConnection_PublishRequestString(conn, "request", "reply", "this is the request");
(...)
// Destroy objects that were created
natsConnection_Destroy(conn);