Redis Cluster

By youfang

Redis Cluster

Redis 集群是一个可以在多个 Redis 节点之间进行数据共享的设施(installation)。

上一篇说到Sentinel存在的问题,使用Cluster能否解决呢?

准备工作

script
1
2
3
4
5
redis 127.0.0.1:6379> SLAVEOF 127.0.0.1 6379
OK
# 取消主从复制
redis 127.0.0.1:6379> SLAVEOF NO ONE
OK

创建集群

./redis-cli --cluster create 192.168.1.101:6379 192.168.1.102:6379 192.168.1.103:6379 --cluster-replicas 1

上面的命令会需要副本,所以用下面的命令创建集群
./redis-cli --cluster create 192.168.1.101:6379 192.168.1.102:6379 192.168.1.103:6379

如果redis中有数据会报错:通过flushdb清空redis

如果有报错:

script
1
[ERR] Not all 16384 slots are covered by nodes.

用以下方式来解决

script
1
2
3
4
5
6
# 集群修复
./redis-cli --cluster fix 192.168.1.101:6379
# 检查集群状态
./redis-cli --cluster check 192.168.1.101:6379
# Redis中查看集群状态
127.0.0.1:6379> cluster info

创建成功!下面来测试。

测试集群

  1. 插入两条数据,再获取看看是否正常?
    项目中正常获取
    1
    2
    3
    127.0.0.1:6379> get aaa
    (error) MOVED 10439 192.168.1.103:6379
    # 不在本机上的会返回让你去哪找它
  2. 如果存在key的103宕机会怎样?
    1
    2
    3
    4
    0-09-20 12:33:04.244 DEBUG 16196 --- [           main] ider$DefaultClusterNodeConnectionFactory : Resolved SocketAddress 192.168.1.103:6379 using for Cluster node at 192.168.1.103:6379
    2020-09-20 12:33:04.244 DEBUG 16196 --- [ main] io.lettuce.core.RedisClient : Connecting to Redis at 192.168.1.103:6379

    org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 5 second(s)
    连接超时,无法获取
  3. 重新执行上面的set再get会怎样?
    1
    2
    3
    4
    2020-09-20 12:35:57.186 DEBUG 12032 --- [           main] ider$DefaultClusterNodeConnectionFactory : Resolved SocketAddress 192.168.1.103:6379 using for Cluster node at 192.168.1.103:6379
    2020-09-20 12:35:57.186 DEBUG 12032 --- [ main] io.lettuce.core.RedisClient : Connecting to Redis at 192.168.1.103:6379

    org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 5 second(s)
    连接超时,无法Set