redis–sentinel基础
1.主从复制高可用?
主从复制问题
- 手动故障转移
- 写能力和存储能力受限(分布式)
2.redis Sentinel架构
redis sentinel可以监控多套主从架构
3.redis Sentinel故障转移
4.redis sentinel安装与配置
安装架构示意图
redis主节点配置
redis-server redis-7000.conf
# 配置
port 7000
daemonize yes #已守护进程运行
pidfile /var/run/redis-7000.pid
logfile "7000.log"
dir "/root/redis/data/"
redis从节点
redis-server redis-7001.conf
redis-server redis-7002.conf
# 配置 slave-1
port 7001
daemonize yes #已守护进程运行
pidfile /var/run/redis-7001.pid
logfile "7001.log"
dir "/root/redis/data/"
slaveof 127.0.0.1 7000
# 配置 slave-2
port 7002
daemonize yes #已守护进程运行
pidfile /var/run/redis-7002.pid
logfile "7002.log"
dir "/root/redis/data/"
slaveof 127.0.0.1 7000
redis-cli -p 7000 info replication # 查看配置是否生效
root@ubuntu-1:~/redis/src# ./redis-cli -p 7000 info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=7001,state=online,offset=7043,lag=1
slave1:ip=127.0.0.1,port=7002,state=online,offset=7043,lag=0
master_repl_offset:7043
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:7042
sentinel配置
# grep -v 排除包含#已经有空行
cat sentinel.conf | grep -v "#" |grep -v "^$" > redis-sentinel-26379.conf
# sentinel配置
port 26381
daemonize yes
dir /root/redis/data/
logfile "26381.log"
sentinel monitor mymaster 127.0.0.1 7000 2 #配置当两个sentinel监测到master宕机,启动转移
sentinel down-after-milliseconds mymaster 30000 #设置监测宕机时间间隔30秒
sentinel parallel-syncs mymaster 1 # 指定了在执行故障转移时, 最多可以有多少个从服务器同时对新的主服务器进行同步
sentinel failover-timeout mymaster 180000 # 指定了故障转移的超时时间
5.redis sentinel java客户端
客户端实现基本原理-step1
客户端实现基本原理-step2
客户端实现基本原理-step3
客户端实现基本原理-step4
5.1 jedis实现sentinel客户端
//获取sentinel的所有节点
Set<String> sentinels = new HashSet<>();
sentinels.add("192.168.56.108:26379");
sentinels.add("192.168.56.108:26380");
sentinels.add("192.168.56.108:26381");
//jedis实现对redis sentinel的客户端连接
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool("mymaster",sentinels);
Jedis jedis = null;
try{
jedis = jedisSentinelPool.getResource();
// jedis.set("hello","world");
String hello = jedis.get("hello");
System.out.println(hello);
}catch (Exception e){
e.printStackTrace();
}finally {
if (jedis != null){
jedis.close();
}
}
5.2 master故障,触发自动故障转移演练
java程序
Set<String> sentinels = new HashSet<>();
sentinels.add("192.168.56.108:26379");
sentinels.add("192.168.56.108:26380");
sentinels.add("192.168.56.108:26381");
//jedis实现对redis sentinel的客户端连接
JedisSentinelPool jedisSentinelPool = new JedisSentinelPool("mymaster",sentinels);
int count = 0;
while (true){
count ++;
Jedis jedis = null;
try {
jedis = jedisSentinelPool.getResource();
int i = new Random().nextInt(100000);
String key = "k-" + i;
String value = "v-" + i;
jedis.set(key,value);
if (count % 100 == 0)
System.out.println(jedis.get(key));
TimeUnit.MILLISECONDS.sleep(10);
}catch (Exception e){
e.printStackTrace();
}finally {
if (jedis != null){
jedis.close();
}
}
}
kill命令杀死master进程,模拟master宕机:当sentinel监测到master宕机,让其中一个slave晋升为master!实现故障自动转移功能