我想编写代码以将数据插入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)
答案 0 :(得分:2)
您可以扩展初始计数器的想法,将其应用于任何操作。
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)