Redis 集群
主从模式
主从模式下从机无法写数据(默认)
redis.conf 有如下配置
不建议修改这个配置 如果修改将会导致从机可以写入数据主机无法同步,导致出现主,从机器数据不一致
replica-read-only yes
实战命令行
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=8001,state=online,offset=2290,lag=0
slave1:ip=127.0.0.1,port=8002,state=online,offset=2290,lag=0
master_replid:5bee5fc2d396f8af65bcdab4a5d7ddc5e31baf83
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:2290
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:2290
➜ redis ./redis-5.0.4/src/redis-cli -h 127.0.0.1 -p 8001 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:8001> set name newshiJ
(error) READONLY You can't write against a read only replica.
127.0.0.1:8001>
键移除
- volatile-lru 利用LRU算法移除设置过过期时间的key
- allkeys-lru 利用LRU算法移除任何key
- volatile-random 移除设置过过期时间的随机key
- allkeys-random 移除随机key
- volatile-ttl 移除即将过期的key(minor TTL)
- voeviction 不移除任何key,只是返回一个写错误(默认选项)
哨兵模式
配置前需要无论主机,从机均需要配置密码,否则在发送故障转移时会出现Redis连接不上的情况
requirepass <password>
masterauth <password>
哨兵模式在会修改 redis.conf sentinel.conf 配置文件,在发生故障转移之后会修改对应Redis进程配置文件的主从关系
在发生故障转移时,Redis集群无法对外提供服务,当完成故障转移之后可以继续对外提供服务
使用java代码连接时直接选择连接哨兵即可,不需要对redis具体服务有感知
@Test
public void sentinel(){
HashSet<String> set = new HashSet<>();
set.add("127.0.0.1:18000");
set.add("127.0.0.1:18001");
set.add("127.0.0.1:18002");
JedisSentinelPool pool = new JedisSentinelPool("mymaster", set, "123456");
while (true){
Jedis jedis = null;
try{
jedis = pool.getResource();
String str = UUID.randomUUID().toString();
jedis.set(str,str);
System.out.println(jedis.get(str));
Thread.sleep(1000L);
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
if(jedis != null){
jedis.close();
}
}
}
}
输出日志如下
Could not get a resource from the pool
Could not get a resource from the pool
Could not get a resource from the pool
Could not get a resource from the pool
cc5f6d81-007e-4d7c-a6bf-318d0f68cd79
e4a96bad-ae3c-4be9-bd32-78b9eb581a87
87d6404a-1363-46cf-ba60-d3ad98e0d97a
7b7585fb-0b2d-4260-8b91-3b40184c4f83
6f871325-91c6-4e17-9001-6b0d945203b2
Disconnected from the target VM, address: '127.0.0.1:35743', transport: 'socket'
哨兵模式健康检查
- 每10秒向主节点发送info命令获取最新的主从结构
- 发现 slave节点,确定主从关系
- 每2秒通过发布订阅功能获取其他哨兵节点的信息, SUBSCRIBE c2 PUBLISH c2 hello-redis
- 交互对节点的"看法"和自身情况
- 每1秒向其他节点发送ping命令进行心跳检查,判断下线
- 心跳检查,失败下线判断的依据
投票选举原则
- 首先过滤不健康的节点
- 选择优先级最高的节点(由 replica-priority 指定)
- 如果优先级无法区分 选择偏移量最大的节点
- 如果偏移量无法区分 选择runid最小的节点