Skip to content

NATS Request Many

This is not an official NATS project

This is a personal project and is not endorsed by the NATS.io community. It is not guaranteed to be maintained or supported.

This is an experimental project

This project is a prototype and should not be used for anything serious. It is not well tested, nor is it guaranteed to be correct.

The nats.deno package (Deno client for NATS) provides a simple way to request many responses from a singe NATS request.

This project is an attempt to implement the same API in Python.

References

How to install

pip install nats-request-many

Example usage

examples/minimal.py
from nats_contrib.request_many import Client
from nats.aio.msg import Msg

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)

logger = logging.getLogger("request_many")


async def main():
    nc = Client()
    await nc.connect(servers="nats://localhost:4222")

    # Subscription callback
    async def cb1(msg: Msg):
        logger.info(f"sub1 received a message sub1 on {msg.subject}")
        await msg.respond(b"OK")

    async def cb2(msg: Msg):
        logger.info(f"sub2 received a message on {msg.subject}")
        await msg.respond(b"OK")

    # First subscription
    sub1 = await nc.subscribe("foo", cb=cb1, queue="queue-1")
    # Second subscription
    sub2 = await nc.subscribe("foo", cb=cb2, queue="queue-2")

    # Request many
    logger.info("sending request to subject 'foo'")
    msgs = await nc.request_many("foo", b"help", max_count=2)
    for msg in msgs:
        print(f"Received a reply: {msg.data.decode()}")

    # Request many with async iterator
    logger.info("sending request to subject 'foo'")
    async with nc.request_many_iter("foo", b"help", max_count=2) as msgs:
        async for msg in msgs:
            print(f"Received a reply: {msg.data.decode()}")

    # Unsubscribe
    await sub1.unsubscribe()
    await sub2.unsubscribe()

    # Close
    await nc.close()


if __name__ == "__main__":
    import asyncio

    asyncio.run(main())

Run the script using:

python examples/minimal.py
2024-02-21 03:05:16,759 - request_many - INFO - sending request to subject 'foo'
2024-02-21 03:05:16,760 - request_many - INFO - sub1 received a message sub1 on foo
2024-02-21 03:05:16,760 - request_many - INFO - sub2 received a message on foo
Received a reply: OK
Received a reply: OK
2024-02-21 03:05:16,761 - request_many - INFO - sending request to subject 'foo'
2024-02-21 03:05:16,762 - request_many - INFO - sub1 received a message sub1 on foo
2024-02-21 03:05:16,762 - request_many - INFO - sub2 received a message on foo
Received a reply: OK
Received a reply: OK

Other works