1

I have 2 functions:

def foo(a,b):
    return a+b

def boo():
    # doing some mapping logic
    if logic:
        return 1
    else:
        return 0

Now, I need to connect it to Nats and from time to time run the mapping funciton boo and sometimes provide foo with a and b parameters out of the given msg to calculate the sum.

I have read the docs but still confused, how step by step make it work.

In my understanding the publisher will send a message with boo subject that will trigger my boo() function. I would like to see a fully explained example how to build it.

SteveS
  • 3,789
  • 5
  • 30
  • 64

1 Answers1

1

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
SteveS
  • 3,789
  • 5
  • 30
  • 64
  • This answer is also can be helpful: https://stackoverflow.com/questions/57360984/nats-subscriber-continuously-listening-to-publisher – SteveS Oct 03 '22 at 09:04