docker部署redis主从和哨兵
docker部署redis主从和哨兵
原文地址:https://www.jianshu.com/p/72ee9568c8ea
1主2从3哨兵
一、前期准备工作
1、电脑装有docker
2、假设本地ip为192.168.2.139
3、各Redis的ip和端口如下:
主:ip:6379
从:ip:6380,ip:6381
sentinel:ip:26379,ip:26380,ip:26381
二、部署主从redis
docker run --name redis6379 --net=host -v $PWD/data6379:/data -d redis:3.2 redis-server --port 6379
docker run --name redis6380 --net=host -v $PWD/data6380:/data -d redis:3.2 redis-server --slaveof 192.168.2.139 6379 --port 6380
docker run --name redis6381 --net=host -v $PWD/data6381:/data -d redis:3.2 redis-server --slaveof 192.168.2.139 6379 --port 6381
执行命名查看redis 同步情况
docker logs redis6379
docker logs redis6380
docker logs redis6381
三、部署sentinel
新建文件 sentinel-26379.conf、sentinel-26380.conf、sentinel-26381.conf
protected-mode no
bind 0.0.0.0
port 26379
daemonize yes
sentinel monitor mymaster 192.168.2.139 6379 2
sentinel down-after-milliseconds master 5000
sentinel failover-timeout mymaster 180000
sentinel parallel-syncs mymaster 1
logfile ""
protected-mode no
bind 0.0.0.0
port 26380
daemonize yes
sentinel monitor mymaster 192.168.2.139 6379 2
sentinel down-after-milliseconds master 5000
sentinel failover-timeout mymaster 180000
sentinel parallel-syncs mymaster 1
logfile ""
protected-mode no
bind 0.0.0.0
port 26381
daemonize yes
sentinel monitor mymaster 192.168.2.139 6379 2
sentinel down-after-milliseconds master 5000
sentinel failover-timeout mymaster 180000
sentinel parallel-syncs mymaster 1
logfile ""
执行命令启动3台sentinel
docker run -it --name sentinel-26379 \
--net=host \
-v $PWD/sentinel-26379.conf:/usr/local/etc/redis/sentinel.conf \
-d redis:3.2 redis-sentinel /usr/local/etc/redis/sentinel.conf
docker run -it --name sentinel-26380 \
--net=host \
-v $PWD/sentinel-26380.conf:/usr/local/etc/redis/sentinel.conf \
-d redis:3.2 redis-sentinel /usr/local/etc/redis/sentinel.conf
docker run -it --name sentinel-26381 \
--net=host \
-v $PWD/sentinel-26381.conf:/usr/local/etc/redis/sentinel.conf \
-d redis:3.2 redis-sentinel /usr/local/etc/redis/sentinel.conf
执行docker logs sentinel-26379
查看启动情况
sentenel会根据master的数据自动把其他salve和sentenel找出来写到自己的配置文件
查看配置文件cat sentinel-26379.conf
发现配置文件多了东西
四、测试连接
新建一个boot工程,配置redis的pom和配置
application.properties
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.2.139:26379,192.168.2.139:26380,192.168.2.139:26381
github地址:https://github.com/hd-eujian/redis.git
码云地址:https://gitee.com/guoeryyj/redis.git
执行单元测试用例
@SpringBootTest
class RedisApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
void contextLoads() {
stringRedisTemplate.opsForValue().set("a","123");
String o = stringRedisTemplate.opsForValue().get("a");
System.out.println(o);
}
}
把其中的master停掉(我的master是6380的redis)
执行docker stop redis6380
查看日志docker logs sentinel-26379
可以看到redis的mater转为6381
再次运行redis代码的单元测试。结果继续有效