ConnectEverything / nats-by-example

Collection of runnable, reference examples using NATS (https://nats.io)
https://natsbyexample.com
152 stars 37 forks source link

NATS Python example equivalent to 'nats reply' and 'nats request` #199

Closed 3goats closed 2 months ago

3goats commented 3 months ago

Hi, Sorry to ask here, but I'm trying to get my head around NATS for a new project.

I'm trying to learn more about NATS and I'm working through the python examples here and here I started with the command line and tested the Request-Response pattern using these commands.

#Terminal 1
nats reply greet.sue 'OK, I CAN HELP!!!'

18:42:54 Listening on "greet.sue" in group "NATS-RPLY-22"
18:42:56 [#0] Received on subject "greet.sue":

I need help!

#Terminal 2
nats reply greet.sue 'OK, I CAN HELP!!!'

18:42:54 Listening on "greet.sue" in group "NATS-RPLY-22"
18:42:56 [#0] Received on subject "greet.sue":

I need help!

#Terminal 3
nats request greet.sue 'I need help!'

18:42:56 Sending request on "greet.sue"
18:42:56 Received with rtt 834.292µs
OK, I CAN HELP!!!

This worked as per the documentation and the two reply services respond in a kind of round-robin way.

I now need the Python equivalents to continue my testing, but all of the examples are trying to be way to clever (at least for where I am currently in my learnings process ) - i.e. they include both the request and reply logic in the same example (e.g. request-reply) which makes it much harder and confusing to understand what's happening.

I can't seem to find any simple examples that break out the Python logic into separate components that behave in the same way as the CLI commands. Can anybody help me out here please.

scottf commented 2 months ago

I assume that this also covers both in example: https://natsbyexample.com/examples/messaging/request-reply/python I think they are made like that a lot of times because you need both sides, especially here in NBE. Some of the clients do have individual example classes, that's probably a good place.

When I explain it...

Request under the covers is just a publish to a subject with a built in reply-to address that some subscriber will use to respond. In the python example I see this where it looks like a request to subject "greet joe" with an empty payload and a timeout to wait for the response.

rep = await nc.request("greet.joe", b'', timeout=0.5)

Reply requires a subscriber to a subject, in this example "greet.joe". When that subscriber gets a message, it formulates a response. Python has respond which under the covers publishes to the reply-to address that was provided with the message.


msg.respond(reply.encode("utf8"))

Those are the basics. And yes generally, they are completely different apps/services that run separately.