gpt4 book ai didi

python - Redis blpop 有时会返回元组,有时不会?

转载 作者:IT王子 更新时间:2023-10-29 06:05:19 24 4
gpt4 key购买 nike

我使用以下代码在我的 Redis 队列中放置/检索项目,但有时在解码 json 转储时会出错,因为返回的项目不是元组而是完整的 json。

这是类(class):

class RedisQueue(object):
"""Simple Queue with Redis Backend"""
def __init__(self, namespace, redis_url='redis://127.0.0.1:6379'):
self.__db = redis.from_url(redis_url)
self.redis_url = redis_url
self.namespace = namespace

def put(self, queue, item):
"""Put item into the queue."""
self.__db.rpush('{0}:{1}'.format(self.namespace, queue), json.dumps(item))

def get(self, queue, block=True, timeout=None):
"""Remove and return an item from the queue.

If optional args block is true and timeout is None (the default), block
if necessary until an item is available."""
key = '{0}:{1}'.format(self.namespace, queue)
if block:
item = self.__db.blpop(key, timeout=timeout)
else:
item = self.__db.lpop(key)

if item is not None:
try:
item = json.loads(item[1])
except ValueError as e:
sys.stderr.write("[ERROR JSON (in queue)] - {1} => {0}\n".format(str(e), str(item)))
return None

return item

我有时会在 :

    if item is not None:
try:
item = json.loads(item[1])
except ValueError as e:
sys.stderr.write("[ERROR JSON (in queue)] - {1} => {0}\n".format(str(e), str(item)))
return None

也就是说:

[ERROR JSON (in queue)] - {"ip": null, "domain": "somedomain.com", "name": "Some user name", "contact_id": 12345, "signature": 
"6f496a4eaba2c1ea4e371ea2c4951ad92f41ddf45ff4949ffa761b0648a22e38"} => end is out of bounds

这是因为 item 是完整的 json,所以 json.loads(item[₁]) 导致错误。但它只是偶尔发生,而不是每次都发生。当我手动检查项目的值时,我有一个元组,键为 0,值(json 字符串)为 1,这是预期的。

为什么有时候,redis 返回 item 中的值,有时候返回一个带有 key,value 的元组?

最佳答案

因为你发出了两个不同的命令,每个命令返回不同的东西。

LPOP返回弹出的项目。它只需要一个键。 BLPOP但是可以针对多个列表运行。因此,它返回从中弹出项目的列表的数组,以及弹出的项目。但是,如果超时到期并且没有可用的项目,它会返回一个 nil 批量数组。

有关这方面的文档很容易在上面的链接中找到。我强烈建议您查看 Redis 文档以了解您使用的命令,以确保您了解相似但不同的命令之间的区别。

在您的代码中,您将调用上述命令之一,但并不总是相同的命令。所以有时你会得到一个元组,而其他人会得到一个字符串。当你阻止时:元组。当你不这样做时:字符串。

为了保持返回值类型的一致性,我总是调用 BLPOP 但不是 bool 值,而是使用用户指定的超时,或者在不想阻止的情况下,一个 block 超时为 0。然后你总是会得到一个元组,尽管你必须捕获 IndexError ,你会在尝试访问空元组的第二个元素时得到。标准的 try/except 子句应该可以做到。

关于python - Redis blpop 有时会返回元组,有时不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37461737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com