redis 阻塞直到 key 存在

2024-04-29

我是 Redis 新手,想知道是否有办法能够await get通过它的键来获取值,直到该键存在。最小代码:

async def handler():
    data = await self._fetch(key)

async def _fetch(key):
    return self.redis_connection.get(key)

如你所知,如果这样key不存在,它return's None。但由于在我的项目中,set将键值对发送到 redis 发生在另一个应用程序中,我想要 redis_connectionget方法阻塞直到键存在。 这样的期望是否有效?


如果不实施某种轮询,就不可能做你想做的事情雷迪斯获取在你的客户身上。在这种情况下,您的客户将不得不执行以下操作:

async def _fetch(key):
    val = self.redis_connection.get(key)
    while val is None:
       # Sleep and retry here
       asyncio.sleep(1)  
       val = self.redis_connection.get(key)
    return val

不过,我要求您完全重新考虑解决此问题所使用的模式。 在我看来,你需要做一些像 Pub/Sub 这样的事情https://redis.io/topics/pubsub https://redis.io/topics/pubsub.

所以执行该操作的应用程序SET成为发布者,并且执行该操作的应用程序GET并等待直到密钥可用成为订阅者。

我对此做了一些研究,看起来你可以使用 asyncio redis 来做到这一点:

  • 订户https://github.com/jonathanslenders/asyncio-redis/blob/b20d4050ca96338a129b30370cfaa22cc7ce3886/examples/pubsub/receiver.py https://github.com/jonathanslenders/asyncio-redis/blob/b20d4050ca96338a129b30370cfaa22cc7ce3886/examples/pubsub/receiver.py.

  • 发件人(发布者):https://github.com/jonathanslenders/asyncio-redis/blob/b20d4050ca96338a129b30370cfaa22cc7ce3886/examples/pubsub/sender.py https://github.com/jonathanslenders/asyncio-redis/blob/b20d4050ca96338a129b30370cfaa22cc7ce3886/examples/pubsub/sender.py

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

redis 阻塞直到 key 存在 的相关文章

随机推荐