Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -----pub/sub------------------
- import asyncio
- from nats.aio.client import Client as NATS
- async def main():
- nc = NATS()
- # Connect to a NATS server
- await nc.connect("nats://localhost:4222")
- # 1. Subscriber: Listening for messages on "updates.news"
- async def message_handler(msg):
- subject = msg.subject
- data = msg.data.decode()
- print(f"Received a message on '{subject}': {data}")
- await nc.subscribe("updates.news", cb=message_handler)
- # 2. Publisher: Sending a message
- await nc.publish("updates.news", b"Hello Python!")
- # Wait a moment to ensure the message is processed
- await asyncio.sleep(1)
- await nc.close()
- if __name__ == '__main__':
- asyncio.run(main())
- ------------------------------------
- async def request_reply_example():
- nc = NATS()
- await nc.connect("nats://localhost:4222")
- # The Responder (Service)
- async def help_request(msg):
- print(f"Received help request: {msg.data.decode()}")
- await nc.publish(msg.reply, b"I can help with that!")
- await nc.subscribe("help.system", cb=help_request)
- # The Requester (Client)
- try:
- # Sends request and waits up to 2 seconds for a response
- response = await nc.request("help.system", b"I need assistance", timeout=2)
- print(f"Response received: {response.data.decode()}")
- except asyncio.TimeoutError:
- print("Request timed out!")
- await nc.close()
- -------------------------------------
- async def jetstream_example():
- nc = NATS()
- await nc.connect("nats://localhost:4222")
- # Create JetStream context
- js = nc.jetstream()
- # Create a stream to store messages (if it doesn't exist)
- await js.add_stream(name="ORDERS", subjects=["orders.>"])
- # Publish to JetStream
- # This is "Acked" - NATS confirms it saved the message to disk
- ack = await js.publish("orders.new", b"Order #1234")
- print(f"Published to JetStream. Sequence: {ack.seq}")
- # Pull Subscriber (fetch messages when ready)
- sub = await js.pull_subscribe("orders.new", "psub")
- msgs = await sub.fetch(1)
- for msg in msgs:
- print(f"Retrieved from storage: {msg.data.decode()}")
- await msg.ack() # Tell NATS we successfully processed it
- await nc.close()
Advertisement