This repository has been archived by the owner on Feb 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 335
/
Copy pathpool_pubsub.py
66 lines (51 loc) · 1.92 KB
/
pool_pubsub.py
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
57
58
59
60
61
62
63
64
65
66
import asyncio
import async_timeout
import aioredis
STOPWORD = "STOP"
async def pubsub():
redis = aioredis.Redis.from_url(
"redis://localhost", max_connections=10, decode_responses=True
)
psub = redis.pubsub()
async def reader(channel: aioredis.client.PubSub):
while True:
try:
async with async_timeout.timeout(1):
message = await channel.get_message(ignore_subscribe_messages=True)
if message is not None:
print(f"(Reader) Message Received: {message}")
if message["data"] == STOPWORD:
print("(Reader) STOP")
break
await asyncio.sleep(0.01)
except asyncio.TimeoutError:
pass
async with psub as p:
await p.subscribe("channel:1")
await reader(p) # wait for reader to complete
await p.unsubscribe("channel:1")
# closing all open connections
await psub.close()
async def main():
tsk = asyncio.create_task(pubsub())
async def publish():
pub = aioredis.Redis.from_url("redis://localhost", decode_responses=True)
while not tsk.done():
# wait for clients to subscribe
while True:
subs = dict(await pub.pubsub_numsub("channel:1"))
if subs["channel:1"] == 1:
break
await asyncio.sleep(0)
# publish some messages
for msg in ["one", "two", "three"]:
print(f"(Publisher) Publishing Message: {msg}")
await pub.publish("channel:1", msg)
# send stop word
await pub.publish("channel:1", STOPWORD)
await pub.close()
await publish()
if __name__ == "__main__":
import os
if "redis_version:2.6" not in os.environ.get("REDIS_VERSION", ""):
asyncio.run(main())