更新时间:2023-11-06 GMT+08:00
分享

Redis重试机制

Redis客户端支持添加自动重试机制,确保在执行Redis操作失败后重试特定次数,这样能大幅度降低暂时性故障影响。例如:发生瞬时的网络抖动、磁盘抖动导致服务暂时不可用或者调用超时的情况下,提高Redis操作的成功概率。

连接DCS单机、主备、读写分离、Proxy集群实例添加Retry配置,退避策略为指数退避(ExponentialBackoff),重试次数上限为3次,并通过retry_on_error配置指定了BusyLoadingError,ConnectionError,TimeoutError三种错误才进行重试,代码片段如下:
    retry = Retry(ExponentialBackoff(), 3)
    pool = BlockingConnectionPool(host=redis_host, port=redis_port,
                                  password=redis_password,
                                  max_connections=50, timeout=3,
                                  socket_timeout=2,
                                  socket_connect_timeout=2,
                                  retry=retry,
                                  retry_on_error=[BusyLoadingError,
                                                  ConnectionError,
                                                  TimeoutError],
                                  health_check_interval=60,
                                  decode_responses=True)
连接DCS集群实例使用了集群错误重试配置(cluster_error_retry_attempts),当遇到TimeoutError、ConnectionError或ClusterDownError时进行重试,默认重试上限为3,代码如下:
    client = Redis(host=redis_host, port=redis_port,
                   password=redis_password,
                   cluster_error_retry_attempts=3,
                   health_check_interval=60, max_connections=50,
                   decode_responses=True)
可以搭配Retry一起使用,示例代码如下:
from redis.backoff import ExponentialBackoff
from redis.retry import Retry
from redis.cluster import RedisCluster

rc = RedisCluster(host='localhost', port=6379, retry=Retry(ExponentialBackoff(), 6), cluster_error_retry_attempts=1)

但是其最大重试次数为 retries * (cluster_error_retry_attempts+1),以上述示例代码为例,最大重试次数为12次。

分享:

    相关文档

    相关产品