这些aioredis中的pub / sub方法是否等效?

时间:2018-11-24 13:17:03

标签: python redis python-asyncio

似乎有两种方法可以进行发布/订阅:

  1. 使用channel.wait_message()和channel.get()
  2. 使用Receiver.iter()

文档说,wait_message()在等待新消息时被阻止。我用修改后的aioredis示例进行了一些测试,它们看起来既有效,也没有阻塞。它们相等吗? 我需要在阅读器中增加一点睡眠吗?如果不是,ioredis如何处理轮询频率?

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()

0 个答案:

没有答案