重做块直到密钥存在 [英] redis block until key exists

查看:44
本文介绍了重做块直到密钥存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Redis的新手,我想知道是否有一种方法可以通过键进行 await 获取一个值,直到该键存在.最少的代码:

I'm new to Redis and was wondering if there is a way to be able to await geting a value by it's key until the key exists. Minimal code:

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

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

如您所知,如果这样的 key 不存在,它将返回 None .但是由于在我的项目中,将键值对设置为redis的设置是在另一个应用程序中进行的,因此我希望redis_connection的 get 方法能够阻塞直到关键存在.这样的期望是否有效?

As you know, if such key doesnt exist, it return's None. But since in my project, seting key value pair to redis takes place in another application, I want the redis_connection get method to block untill key exists. Is such expectation even valid?

推荐答案

如果不在客户端上实施某种类型的池 redis GET ,就无法完成您尝试做的事情.在这种情况下,您的客户将必须执行以下操作:

It is not possible to do what you are trying to do without implementing some sort of pooling redis GET on your client. On that case your client would have to do something like:

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 .

However I would ask you to completelly reconsider the pattern you are using for this problem. It seems to me that what you need its to do something like Pub/Sub https://redis.io/topics/pubsub.

因此执行 SET 的应用将成为发布者,而执行 GET 并等待密钥可用的应用将成为订阅者.

So the app that performs the SET becomes a publisher, and the app that does the GET and waits until the key is available becomes the subscriber.

我对此进行了一些研究,看起来您可以使用asyncio_redis做到这一点:

I did a bit of research on this and it looks like you can do it with asyncio_redis:

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

希望这会有所帮助.

这篇关于重做块直到密钥存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆