redis的集群分为三种,分别是主从集群,哨兵集群和分片集群
这篇先为大家带来如何快速在docker中搭建redis哨兵集群
一、首先我们先明确哨兵集群的结构图
二、我们是搭建三个节点的哨兵集群,三个sentinel实例信息如下
三、 首先,创建三个文件夹
# 进入/tmp目录
cd /tmp
# 创建目录
mkdir s1 s2 s3
四、在s1目录创建一个sentinel.conf文件
vi s1/sentinel.conf
# 添加下面内容
port 27001
# 节点的ip
sentinel announce-ip 192.168.137.138
# 客观下线的节点数量
sentinel monitor mymaster 192.168.137.138 7001 2
# 选主的时候,与master断开连接时间超过这个值的节点会被排除掉
sentinel down-after-milliseconds mymaster 5000
# 切换sentinel的时间间隔
sentinel failover-timeout mymaster 60000
# 数据存储目录
dir "/tmp/s1"
五、然后将s1/sentinel.conf文件拷贝到s2、s3两个目录中(在/tmp目录执行下列命令)
# 方式一:逐个拷贝
cp s1/sentinel.conf s2
cp s1/sentinel.conf s3
# 方式二:管道组合命令,一键拷贝
echo s2 s3 | xargs -t -n 1 cp s1/sentinel.conf
六、 修改s2、s3两个文件夹内的配置文件,将端口分别修改为27002、27003
sed -i -e 's/27001/27002/g' -e 's/s1/s2/g' s2/sentinel.conf
sed -i -e 's/27001/27003/g' -e 's/s1/s3/g' s3/sentinel.conf
七、启动3个redis实例
# 第1个
redis-sentinel s1/sentinel.conf
# 第2个
redis-sentinel s2/sentinel.conf
# 第3个
redis-sentinel s3/sentinel.conf
那么我们如何在JAVA代码中实现RedisTemplate集成哨兵机制呢?
一、首先在pom文件中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
二、在yml文件中配置redis地址
spring:
redis:
sentinel:
master: mymaster
nodes:
- 192.168.137.138:27001
- 192.168.137.138:27002
- 192.168.137.138:27003
三、在启动类中配置读写分离的一个bean,启动读写分离
@Bean
public LettuceClientConfigurationBuilderCustomizer clientConfigurationBuilderCustomizer(){
return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
}