连接dcs单机、主备、读写分离、proxy集群实例-j9九游会登录
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失败。
|
参数 |
默认值 |
说明 |
|---|---|---|
|
connection_pool |
none |
连接池 |
|
参数 |
默认值 |
说明 |
|---|---|---|
|
max_connections |
50 |
连接池最大连接数 |
|
timeout |
20 |
连接池耗尽后获取连接的最大等待时间 |
|
参数 |
默认值 |
说明 |
|---|---|---|
|
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 |
默认所有响应都以字节形式返回 |
|
参数 |
默认值 |
说明 |
|---|---|---|
|
backoff |
- |
退避策略 |
|
retries |
- |
重试次数,可以是负数,支持永远重试 |
|
supported_errors |
connectionerror timeouterror socket.timeout |
触发重试的支持错误类型 |
|
参数 |
默认值 |
说明 |
|---|---|---|
|
cap |
0.512 |
最大退避时间(秒) |
|
base |
0.008 |
基本退避时间(秒) |
相关文档
意见反馈
文档内容是否对您有帮助?
如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨