Redis 学习-Redis Sentinel

主从服务,在主服务挂掉以后须要咱们手动操做,从新设置其余服务来充当主服务。html

而 sentinel 能够自动完成这一动做。node

1、启动 redis 服务

启动 redis 服务能够查看前面章节,咱们须要 1 主 2 从。redis

主 127.0.0.1:6379spring

从 127.0.0.1:6380、127.0.0.1:6381dom

 

2、启动 sentinel 服务

1. 配置文件 sentinel.confspa

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. 查看服务信息code

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

4. 最少启动 3 个 sentinel 服务 htm

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

3 个 sentinel 服务分别为:

127.0.0.1:2637九、127.0.0.1:26380、127.0.0.1:26381

 

3、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 服务会恢复正常。

 

4、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,不然故障转移可能会出现异常。

相关文章
相关标签/搜索