Python aioredis中的这些发布/订阅方法是否等效?
似乎有两种方法可以进行发布/订阅:Python aioredis中的这些发布/订阅方法是否等效?,python,redis,python-asyncio,Python,Redis,Python Asyncio,似乎有两种方法可以进行发布/订阅: 使用channel.wait_message()和channel.get() 使用Receiver.iter() 文档说等待新消息时wait_message()被阻塞。我用一个修改过的aioredis示例做了一些测试,它们似乎都能工作,并且没有阻塞。它们相等吗? 我需要在阅读器中添加一个小睡眠吗?如果没有,aioredis如何处理轮询频率 import asyncio import aioredis import random from itertools i
import asyncio
import aioredis
import random
from itertools import count
async def reader(ch):
# while await ch.wait_message():
# msg = await ch.get_json()
async for msg in ch.iter(encoding='utf-8'):
print("Got Message:", msg)
**# await asyncio.sleep(.1) # is this necessary?**
async def sender(pub):
while True:
pub.publish_json('chan:1', ["Hello", "world"])
await asyncio.sleep(random.randint(1, 5))
async def foo():
while True:
print('bar')
await asyncio.sleep(random.random())
async def main():
pub = await aioredis.create_redis(
'redis://localhost')
sub = await aioredis.create_redis(
'redis://localhost')
ch1, = await sub.subscribe('chan:1')
tsk = asyncio.ensure_future(reader(ch1))
tsk1 = asyncio.ensure_future(foo())
tsk2 = asyncio.ensure_future(sender(pub))
await foo()
await sub.unsubscribe('chan:1')
await tsk
tsk1.cancel()
await tsk1
tsk2.cancel()
await tsk2
sub.close()
pub.close()
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
try:
pass
except KeyboardInterrupt:
for task in asyncio.all_tasks():
task.cancel()