Finally figured it out and posting for others:
I have built the listener function:
import asyncio
import ujson
from nats.aio.client import Client as NATS
async def app():
nc = NATS()
async def disconnected_cb():
print("Got disconnected...")
async def reconnected_cb():
print("Got reconnected...")
await nc.connect("127.0.0.1",
reconnected_cb=reconnected_cb,
disconnected_cb=disconnected_cb,
max_reconnect_attempts=-1)
async def slot_filling(msg):
print(msg)
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
data_json = ujson.loads(data)
print(f"Received a message on {subject} {reply}: {data}")
ret = foo(query=data_json.get("a"),
function_name=data_json.get("func_name"))
await nc.publish(reply, ret.encode())
# Use queues named 'channel_1_queue' and 'channel_2_queue' for distributing requests
# among subscribers.
await nc.subscribe("channel_1", "channel_1_queue", foo)
await nc.subscribe("channel_2", "channel_2_queue", boo)
print("Listening for requests on 'channel_1' and 'channel_2' subjects...")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(app())
loop.run_forever()
loop.close()
Be sure foo
and boo
functions are "decorated" with async
before declaration:
async def foo(....):
Then I am running the publisher with the relevant inputs and docker:
docker run -i --rm --network host --entrypoint /usr/local/bin/nats natsio/nats-box req channel_1 '{"a": (1,2), "func_name": foo}' | jq .
Where jq is optional to display the json in human readable format.
Be sure you have NATS docker up and running:
docker run -d --name nats -p 4222:4222 -p 6222:6222 -p 8222:8222 nats:alpine3.15 -m 8222