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:
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 responsesub, 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 replymsg, err := sub.NextMsg(time.Second)if err !=nil { log.Fatal(err)}// Use the responselog.Printf("Reply: %s", msg.Data)
Connection nc =Nats.connect("nats://demo.nats.io:4222");// Create a unique subject nameString uniqueReplyTo =NUID.nextGlobal();// Listen for a single responseSubscription sub =nc.subscribe(uniqueReplyTo);sub.unsubscribe(1);// Send the requestnc.publish("time", uniqueReplyTo,null);// Read the replyMessage msg =sub.nextMessage(Duration.ofSeconds(1));// Use the responseSystem.out.println(newString(msg.getData(),StandardCharsets.UTF_8));// Close the connectionnc.close();
// set up a subscription to process the requestconstsc=StringCodec();nc.subscribe("time", {callback: (_err, msg) => {msg.respond(sc.encode(newDate().toLocaleTimeString())); },});// create a subscription subject that the responding send replies toconstinbox=createInbox();constsub=nc.subscribe(inbox, { max:1,callback: (_err, msg) => {t.log(`the time is ${sc.decode(msg.data)}`); },});nc.publish("time", Empty, { reply: inbox });
require'nats/client'require'fiber'NATS.start(servers:["nats://127.0.0.1:4222"]) do|nc|Fiber.newdo f =Fiber.current nc.subscribe("time") do|msg, reply| f.resume msgend nc.publish("time",'example',NATS.create_inbox)# Use the response msg =Fiber.yieldputs"Reply: #{msg}"end.resumeend
natsConnection *conn =NULL;natsStatus s = NATS_OK;s =natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);// Publish a message and provide a reply subjectif (s == NATS_OK) s =natsConnection_PublishRequestString(conn,"request","reply","this is the request");(...)// Destroy objects that were creatednatsConnection_Destroy(conn);