社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Redis

这些方法在aioredis中是等价的吗?

solst • 5 年前 • 919 次点击  

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

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

医生说wait_message()在等待新消息时被阻塞。我用一个修改过的aioredis示例做了一些测试,它们看起来既有效又不阻塞。它们相等吗? 我需要在阅读器中添加一个小睡眠吗?如果不是,那么aioredis如何处理投票频率?

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()
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49893
 
919 次点击