在python中订阅redis频道时使用了意外的功能

mwngjboj  于 2021-06-07  发布在  Redis
关注(0)|答案(1)|浏览(320)

我对用python操作redis服务器的连接很陌生。我想知道有什么办法可以解决以下情况:
我要做的是

There are three mainly step for my program:
1. subscribe channel on Redis
2. Get the message from Redis and convert to custom model(or dict)
3. Sent the custom model to my server using socketio

我写的是

async def subscribeRedisChannel():
    for item in r.subscriber.listen():
        logger.info("[DEBUG]Checkin Result from Redis: {}".format(item))
        if item['type'] == 'message':
            checkInSubject.on_next(item)
            await sio.emit('punchByEquipment', data = keep.value)

环境

python3
socketio
asyncio
rx
redis

我面临的问题

if I call the subscribeRedisChannel function in my main function, the program will be hang on it. Other program cannot work correctly.
hjzp0vay

hjzp0vay1#

对于那些有相同或相似问题的人。
在这个问题中,我意识到主要的问题是使用阻塞消息。首先,我按照旧版本的示例代码来实现redis和我的程序之间的连接机制

for message in p.listen():
     # do something with the message

不过,你可以直接打电话 get_message() 以非阻塞机制监听信道。对于用法示例,您可以在测试代码中找到它

while True:
     message = p.get_message()
     if message:
         # do something with the message
     time.sleep(0.001)  # be nice to the system :)

如果你正在寻找具体的解释,请在其他线程中检查此答案。

相关问题