zoukankan      html  css  js  c++  java
  • Redis 学习-Redis Sentinel

    主从服务,在主服务挂掉之后需要我们手动操作,重新设置其他服务来充当主服务。

    而 sentinel 可以自动完成这一动作。

    一、启动 redis 服务

    启动 redis 服务可以查看前面章节,我们需要 1 主 2 从。

    主 127.0.0.1:6379

    从 127.0.0.1:6380、127.0.0.1:6381

    二、启动 sentinel 服务

    1. 配置文件 sentinel.conf

    daemonize yes # 是否守护进程启动
    pidfile "/var/run/redis-sentinel-26379.pid" # pid文件
    logfile "26379.log" # 日志文件
    dir "/usr/local/src/redis/redis-5.0.7/data" # 工作空间
    sentinel monitor mymaster 127.0.0.1 6379 2 # redis 主节点的 ip 和端口,即使单机多实例也不能使用127.0.0.1

    2. 启动服务

    redis-sentinel sentinel.conf

    3. 查看服务信息

    redis-cli -p 26379 # 访问服务
    info # 查看服务信息

    4. 最少启动 3 个 sentinel 服务 

    将配置文件分别复制出来端口号为 26380、26381的两个服务。

    3 个 sentinel 服务分别为:

    127.0.0.1:26379、127.0.0.1:26380、127.0.0.1:26381

    三、Java 集成 sentinel

    1. 引入 jar 包

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.0</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

    2. 客户端

    String masterName = "mymaster";
    Set<String> set = new HashSet<>();
    set.add("192.168.116.128:26379");
    set.add("192.168.116.128:26380");
    set.add("192.168.116.128:26381");
    
    JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, set);
    
    while (true) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            int index = new Random().nextInt(100000);
            String key = "key-" + index;
            String value = "value-" + index;
            jedis.set(key, value);
            System.out.println(key + " value is " + jedis.get(key));
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    执行上面程序时,可以将主节点进程杀死观察一下。

    在控制台输出异常大约一两分钟后,senticenl 服务会恢复正常。

    四、SpringBoot 集成 sentintl

    1. SpringBoot 集成 redis 参考博客:

    https://www.cnblogs.com/zeng1994/p/03303c805731afc9aa9c60dbbd32a323.html

    2. 在此基础上仅仅修改配置文件:

    spring.redis.sentinel.master=mymaster # sentinel config 中配置的
    spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 # 3个sentinel服务
    
    # 下面配置注释掉
    #spring.redis.database=0
    #spring.redis.host=192.168.116.128
    #spring.redis.port=6379

    3. 注意点:

    即使单机多实例情况下,配置文件中也不要使用 127.0.0.1,而应该使用真实 IP,否则故障转移可能会出现异常。

  • 相关阅读:
    计时器chronometer补充
    SpannableString富文本
    java数据结构整理(二)
    Java数据结构整理(一)
    graphical Layout调大一点
    eclipse快捷键
    弹出式菜单(下拉菜单)实现——PopupMenu
    二级横向菜单实现——ListView
    java求两个集合的差集
    Java中String的split()方法的一些需要注意的地方
  • 原文地址:https://www.cnblogs.com/libra0920/p/12084047.html
Copyright © 2011-2022 走看看