我想实施redis-sentinel. 以下代码片段显示了我所做的:
import redis
from redis.sentinel import Sentinel
from .config import redis_config
redis_client = None
def create_redis_client():
global redis_client
SENTINEL_PORT = int(redis_config["redis.sentinel.port"])
sentinel = Sentinel([(redis_config["redis.server.master"], SENTINEL_PORT),
(redis_config["redis.server.slave1"], SENTINEL_PORT),
(redis_config["redis.server.slave2"], SENTINEL_PORT)])
# sentinel_kwargs={"password": redis_config["redis.server.password"]})
# you will need to handle yourself the connection to pass again the password
# and avoid AuthenticationError at redis queries
host, port = sentinel.discover_master(redis_config["redis.master.name"])
print(f"Redis Sentinel Host: {host}")
print(f"Redis Sentinel Port: {port}")
redis_client = redis.StrictRedis(
host=host,
port=port,
password= redis_config["redis.server.password"]
)
def get_redis_client():
if redis_client is None:
create_redis_client()
return redis_client
else:
return redis_client
这里redis_config只有这样的字典:
# sentinel
redis_config = {
"redis.server.master": "MASTER_IP",
"redis.server.slave1": "SLAVE_IP",
"redis.server.slave2": "SLAVE_IP",
"redis.sentinel.port": "26379",
"redis.master.name": "mymaster",
"redis.server.password": "SAMPLE_PASSWORD"
}
我按照这个解决方案来实施redis-sentinel. 但令人惊讶的是,我突然收到以下错误:
redis.exceptions.ReadOnlyError: You can't write against a read only replica.
似乎是当任何故障发生时,哨兵并没有改变主人。为什么会这样?这不是第一次发生,这种情况以前发生过一次。实施好吗?