云服务器内容精选

  • 连接D CS 单机、主备、读写分离、Proxy集群实例 from redis.backoff import ExponentialBackoff from redis.retry import Retry from redis.client import Redis from redis.connection import BlockingConnectionPool from redis.exceptions import ( BusyLoadingError, ConnectionError, TimeoutError ) redis_client = None def create_redis_client(context): logger = context.getLogger() redis_address = context.getUserData("redis_ip_address") redis_host = redis_address.split(":")[0] redis_port = redis_address.split(":")[1] redis_password = context.getUserData("redis_password") logger.info("redis host={}".format(redis_host)) logger.info("redis port={}".format(redis_port)) retry = Retry(ExponentialBackoff(), 3) pool = BlockingConnectionPool(host=redis_host, port=redis_port, password=redis_password, max_connections=20, timeout=3, socket_timeout=2, socket_connect_timeout=2, retry=retry, retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError], health_check_interval=60, decode_responses=True) return Redis(connection_pool=pool) def initializer(context): global redis_client redis_client = create_redis_client(context) redis_client.ping() def handler(event, context): logger = context.getLogger() redis_client.set('foo', 'bar') value = redis_client.get('foo') logger.info("redis get key foo value={}".format(value)) return value 客户端使用连接池时不要将获取连接的操作放在初始化函数 initializer 方法中,否则只会在初始化时获取一个连接而导致连接池使用无效。当网络抖动时可能会使已获取的连接断连,后续复用该实例的并发请求时可能会因断连而访问redis失败。 表1 Redis配置 参数 默认值 说明 connection_pool None 连接池 表2 BlockingConnectionPool配置 参数 默认值 说明 max_connections 50 连接池最大连接数 timeout 20 连接池耗尽后获取连接的最大等待时间 表3 Connection配置 参数 默认值 说明 host localhost 连接Redis实例的IP地址/ 域名 port 6379 连接端口号 password - 连接密码 socket_timeout None 请求等待响应的超时时间(秒) socket_connect_timeout None 连接超时时间(秒) retry None 失败后重试策略 retry_on_error None 需要重试的错误列表 health_check_interval 0 Redis连接健康检查间隔 decode_responses False 默认所有响应都以字节形式返回 表4 Retry配置 参数 默认值 说明 backoff - 退避策略 retries - 重试次数,可以是负数,支持永远重试 supported_errors ConnectionError TimeoutError socket.timeout 触发重试的支持错误类型 表5 ExponentialBackoff配置 参数 默认值 说明 cap 0.512 最大退避时间(秒) base 0.008 基本退避时间(秒) 父主题: 示例代码