-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubscriptions.py
More file actions
53 lines (40 loc) · 1.78 KB
/
subscriptions.py
File metadata and controls
53 lines (40 loc) · 1.78 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
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!r}") # noqa: T201
cb_lock.set()
async with (
# When subscribing you can set callback.
# In that case CallbackSubscription is returned.
# This type of subscription cannot be iterated.
nats.subscribe("cb-subj", callback=callback) as cb_sub,
# When callback is not set, you get a subscription
# that should be used along with `async for`
nats.subscribe("iter-subj") as iter_sub,
# Subscriptions with queue argument create
# subscription with a queue group to distribute
# messages along all subscribers.
nats.subscribe("queue-subj", queue="example-queue") as queue_sub,
):
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!r}") # noqa: T201
async for message in queue_sub:
print(f"[FROM_QUEUED] {message.payload!r}") # 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())