带Redis pubsub的FastAPI

2024-06-16 04:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种解决方案,在不使用线程的情况下,将FastAPI与Redis pubsub一起使用。我到处寻找使用aioredis、redis py和web套接字的解决方案,但我似乎无法让它们工作

我希望有一个运行unicorn服务器的简单示例,在订阅Redis频道时,在接收消息时打印消息。我使用的是Python3.6.12,因此首选Python3.6解决方案

谢谢

下面是最近在没有FASTapi的情况下对aioredis的尝试,在另一个终端的Redis上发布时无法获取打印消息

import asyncio
import aioredis
import async_timeout

STOPWORD = "STOP"


async def pubsub():
    redis = aioredis.Redis.from_url(
        "redis://:password@localhost:6379", max_connections=10, decode_responses=True
    )
    await redis.publish("channel:1", "abc")
    psub = redis.pubsub()
    async def reader(channel: aioredis.client.PubSub):
        while True:
            try:
                async with async_timeout.timeout(1):
                    # print("trying to get message")
                    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()



if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(pubsub())
    print('finished')

Tags: importredisasynciotruemessageasynctimeoutchannel