代码之家  ›  专栏  ›  技术社区  ›  Diego L

Python中的redis是异步的吗?

  •  0
  • Diego L  · 技术社区  · 11 月前

    我有以下Python代码:

    import redis
    
    from app.infra.services.notifications import INotifier
    from app.schemas.notification import NotificationMessage
    from app.config import settings
    
    
    REDIS_CLIENT_PUBSUB = redis.StrictRedis(
        host=settings.REDIS_HOST,
        port=settings.REDIS_PORT,
        password=settings.REDIS_PASSWORD,
    )
    
    class RedisNotifier(INotifier):
        def __init__(self):
            self.redis_client = REDIS_CLIENT_PUBSUB
    
        async def send_notification(self, room: str, notification: NotificationMessage) -> None:
            await self.redis_client.publish(room, notification.json())
    
    
    redis_notifier = RedisNotifier()
    

    我有一个用FastAPI编写的web应用程序,它将使用redis_notifier向频道发布消息。我的问题是,它是否真的: self.redis-client.publish(文件室,notification.json()) 它是异步的,也就是说,我的web应用程序能够在发布完成时放弃这个协程并做其他事情吗? 我对redis和aioredis库有点困惑,我不知道我的代码是否有意义,或者我做错了什么

    1 回复  |  直到 11 月前
        1
  •  0
  •   Raj Dubey    11 月前

    这里的Redis是同步的,这意味着它会阻止代码的执行,直到它完成操作。

    您可以使用 aioredis asyncio redis

    https://aioredis.readthedocs.io/en/latest/

    https://pypi.org/project/asyncio-redis/

        2
  •  0
  •   Mirko Ortensi    11 月前

    aioredis的最新版本是2.0.1,可追溯到2021年12月。aioredis已合并到redis-py 4.2.0rc1+中,因此可以通过redis-py的标准安装来获得它。

    在此处查找示例 https://redis-py.readthedocs.io/en/stable/examples/asyncio_examples.html