如何从 sentinel url 创建 redis python 客户端?

How to create redis python client from sentinel url?

我有 url 作为

BROKER_URL = 'sentinel://192.168.10.1:26379/0;sentinel://192.168.10.2:26379/0;sentinel://192.168.10.3:26379/0'

在此,redis在192.168.10.1192.168.10.2192.168.10.3上是运行。一个节点是主节点,其他节点是从节点。如果 master 宕机,其他节点代替 master。

我查看了redis客户端,但是没有方法,我们可以像我给的那样提供url。

我们必须提供主机名和端口。就我而言,master 将是这 3 个中的任何一个。

检查 https://github.com/andymccurdy/redis-py/blob/master/README.rst#sentinel-support

处的 redis-py 代码库 readme.md

像这样:

from redis.sentinel import Sentinel
sentinel = Sentinel([('192.168.10.1', 26379), ('192.168.10.2',26379), ('192.168.10.3',26379)], socket_timeout=0.1)

master = sentinel.master_for('master-name', socket_timeout=0.1)

The master and slave objects are normal StrictRedis instances with their connection pool bound to the Sentinel instance. When a Sentinel backed client attempts to establish a connection, it first queries the Sentinel servers to determine an appropriate host to connect to. If no server is found, a MasterNotFoundError or SlaveNotFoundError is raised.

实际情况是,如果你为redis集群构建Sentinel,你不需要直接连接redis服务器。按照上面的方法,首先连接到 Sentinel,然后使用 master_for 查询要连接的适当主机。只有这样,如果 master 挂了,你的客户端才能被引导到新的 master。

而上面代码中的master-name,你应该在sentinel.conf中指定 在

sentinel monitor <master-group-name> <ip> <port> <quorum>

像这样:

sentinel monitor mymaster 127.0.0.1 6379 2

要与 python redis client 连接,如果您需要进行身份验证并设置密码,则可以按照以下步骤进行操作:

from redis.sentinel import Sentinel
sentinel = Sentinel([('192.168.10.1', 26379),
                     ('192.168.10.2',26379),
                     ('192.168.10.3',26379)],
                   sentinel_kwargs={'password': YOUR_REDIS_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(YOUR_REDIS_DB_MASTER)
redis_client = redis.StrictRedis(
            host=host,
            port=port,
            password= YOUR_REDIS_PASSWORD
        )

您可以直接使用像

这样的简单查询来测试它
redis_client.exists("mykey")

当然,如果您没有设置密码,您可以删除 redis_client 实例中的 sentinel_kwargs={'password': YOUR_REDIS_PASSWORD}password 属性。

如果设置失败,您可能会遇到 MasterNotFoundError(如果重要发现失败)或 AuthenticationError(如果您没有在正确的位置传递正确的密码或密码参数)