Spring Data Redis 教程

Spring Data Redis 哨兵支持

哨兵(Sentinal)是一个分布式系统,用于对主从结构中的每台服务器进行监控,当出现故障时通过投票机制选择新的 master 并将所有的 slave 连接到新的 master。

哨兵的作用

  • 监控

    • 不断的检查 master 和 slave 是否正常运行

    • master 存活检测、master 与 slave 运行情况检测

  • 通知(提醒)

  • 自动故障转移

    • 断开 master 与 slave 连接,选取一个 slave 作为 master,将其他的 slave 连接到新的 master,并告知客户端新的服务器地址

注意:

(1)哨兵也是一台 redis 服务器,只是不提供数据服务

(2)通常哨兵配置的数量为单数

对于高可用的 Redis,Spring Data Redis 支持 Redis Sentinel(Redis 哨兵模式),可以使用 RedisSentinelConfiguration 配置类为 Redis 连接配置哨兵。如下例所示:

/**
 * Jedis 驱动
 */
@Bean
public RedisConnectionFactory jedisConnectionFactory() {
    RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
        .master("mymaster")
        .sentinel("127.0.0.1", 26379)
        .sentinel("127.0.0.1", 26380);
    return new JedisConnectionFactory(sentinelConfig);
}

/**
 * Lettuce 驱动
 */
@Bean
public RedisConnectionFactory lettuceConnectionFactory() {
    RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
        .master("mymaster")
        .sentinel("127.0.0.1", 26379)
        .sentinel("127.0.0.1", 26380);
    return new LettuceConnectionFactory(sentinelConfig);
}

注意,RedisSentinelConfiguration 也可以使用 PropertySource 定义,它允许您设置以下属性:

配置属性

  • spring.redis.sentinel.master    主节点的名称。

  • spring.redis.sentinel.nodes    逗号分隔的 “主机:端口” 对列表。

  • spring.redis.sentinel.username    使用 Redis Sentinel 进行身份验证时应用的用户名(需要 Redis 6)

  • spring.redis.sentinel.password    使用 Redis Sentinel 进行身份验证时应用的密码

有时,需要与其中一个哨兵直接互动。使用 RedisConnectionFactory.getSentinelConnection() 或 RedisConnection.getSentinelCommands() 可以让您访问配置的第一个活动哨兵。

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号