gpt4 book ai didi

python - 连接断开时重试 Redis 操作

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

我想编写代码将数据插入 Redis。首先,它应该连接 Redis 服务器,如果失败则重试。连接后,它应该执行 hset()set() 等命令。如果连接中断,我如何重试这些命令?

这是我目前所拥有的,它只处理连接步骤中的重试。

while cnt < 11:
try:
r.ping()
break

except redis.ConnectionError:
time_sleep = cnt * 5
time.sleep(time_sleep)
r = redis.Redis(host='10.23.*.*', port=6379, db=0)
cnt += 1
print cnt
if cnt == 11:
sys.exit(-1)
r.hset(field,keys,1)

最佳答案

您可以扩展您最初的反击想法,将其应用于任何操作。

max_retries = 10
count = 0

r = redis.Redis(host='10.23.*.*', port=6379, db=0)

def try_command(f, *args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except redis.ConnectionError:
count += 1

# re-raise the ConnectionError if we've exceeded max_retries
if count > max_retries:
raise

backoff = count * 5

print('Retrying in {} seconds'.format(backoff)
time.sleep(backoff)

r = redis.Redis(host='10.23.*.*', port=6379, db=0)

# this will retry until a result is returned
# or will re-raise the final ConnectionError
try_command(r.hset, field, keys, 1)

关于python - 连接断开时重试 Redis 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773114/

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