-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubscriptions.py
More file actions
56 lines (40 loc) · 1.77 KB
/
subscriptions.py
File metadata and controls
56 lines (40 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
from natsrpy import Message, Nats
async def main() -> None:
"""Main function to run the example."""
nats = Nats(["nats://localhost:4222"])
await nats.startup()
cb_lock = asyncio.Event()
async def callback(message: Message) -> None:
print(f"[FROM_CALLBACK] {message.payload}") # noqa: T201
cb_lock.set()
# When subscribing you can set callback.
# In that case CallbackSubscription is returned.
# This type of subscription cannot be iterated.
cb_sub = await nats.subscribe("cb-subj", callback=callback)
# When callback is not set, you get a subscription
# that should be used along with `async for`
# loop, or alternatively you can call
# `await iter_sub.next()` to get a single message.
iter_sub = await nats.subscribe("iter-subj")
# Subscriptions with queue argument create
# subscription with a queue group to distribute
# messages along all subscribers.
queue_sub = await nats.subscribe("queue-subj", queue="example-queue")
await nats.publish("cb-subj", "message for callback")
await nats.publish("iter-subj", "message for iterator")
await nats.publish("queue-subj", "message for queue sub")
# We can unsubscribe after a particular amount of messages.
await iter_sub.unsubscribe(limit=1)
await cb_sub.unsubscribe(limit=1)
await queue_sub.unsubscribe(limit=1)
async for message in iter_sub:
print(f"[FROM_ITERATOR] {message.payload}") # noqa: T201
async for message in queue_sub:
print(f"[FROM_QUEUED] {message.payload}") # noqa: T201
# Making sure that the message in callback is received.
await cb_lock.wait()
# Don't forget to call shutdown.
await nats.shutdown()
if __name__ == "__main__":
asyncio.run(main())