Redis Cluster 是 Redis 提供的分布是解决方案,有效的解决了 Redis 分布式方面的需求,当遇到单机内存、并发、流量等瓶颈时,就可以考虑 cluster 架构达到负载均衡的目的。
Redis Cluster 采用虚拟分槽(slot),虚拟槽分区巧妙地利用了 hash 空间,使用分散度良好的哈希函数将所有数据映射到一个固定范围内的整数集合,整数定义为槽(slot)。Redis Cluster 槽的范围是 0 ~ 16383,槽是集群内数据管理和迁移的基本单位。采用大范围槽的主要目的是为了方便数据的拆分和集群的扩展,每个节点负责一定数量的槽。
节点准备
不管是手动搭建还是利用 redis-trib
,首先我们需要一定数量的 redis 服务器,本篇中我们采用本机启动 6 个节点,3 主 3 从。
创建配置文件
1 | port 8001 |
对于每个不同的节点,修改上述配置文件中 8001
即可。我们创建了 8001
,8002
,8003
,8004
,8005
,8006
六个节点。
Redis Cluster 启动时会同时占用 当前端口号+10000 的第二个高端口号,该端口号的作用为:
This second high port is used for the Cluster bus, that is a node-to-node communication channel using a binary protocol
启动 Redis
我们使用 docker 来启动 redis:
1 | redis-server 8001/redis-8001.conf 2>&1 > 8001/logs & |
查看端口情况
1 | $ netstat -tulnp |
手动搭建
节点握手
使用 redis-cli
连接 redis cluster 的时候需要带上 -c
选项,它提供了基础的 redis cluster 支持。
1 | $ redis-cli -c -p 8001 |
分配槽
1 | # 给 master-1 分配槽 |
配置从节点
1 | $ redis-cli -c -p 8004 |
查看集群最终节点状态
1 | $ redis-cli -c -p 8001 |
测试数据
使用 cluster keyslot
来查看 key 会被分配到哪个槽中
1 | 127.0.0.1:8001> cluster keyslot key:{10}:111 |
为上面三个 key 设置值:
1 | 127.0.0.1:8001> set key:{10}:111 value_of_key:{10}:111 |
可以看到,在 master-1 上设置 key:{test}:111
时自动重定向到了 master-2,在 master-2 上设置 key:{hu}:111
时自动重定向到了 master-3。
获取值:
1 | 127.0.0.1:8004> get key:{test}:111 |
可以看到在获取值的时候,如果不是本节点所持有的槽,会自动重定向到相应的主节点去获取(即使当前节点是对应主节点的 slave,也就是说 slave 在 redis cluster 中只起到了替换主节点的作用)。
利用 redis-trib 搭建
Redis 在其源码包中附带了一个 ruby 脚本 redis-trib.rb
用来快速搭建 redis cluster,并且 Redis 官网的 tutorial 也指出:
In practical terms redis-trib here did very little to help us, it just sent a CLUSTER MEET message to the node, something that is also possible to accomplish manually. However redis-trib also checks the state of the cluster before to operate, so it is a good idea to perform cluster operations always via redis-trib even when you know how the internals work.
之前我们已经启动了 6 个节点,下面我们用 redis-trib
来搭建集群:
1 | ./redis-trib.rb create --replicas 1 127.0.0.1:8001 127.0.0.1:8002 127.0.0.1:8003 127.0.0.1:8004 127.0.0.1:8005 127.0.0.1:8006 |
这样就完成了,整个过程中我们只需要在 Can I set the above configuration? (type ‘yes’ to accept): 的地方输入 yes,redis-trib
会为我们完成手动需要的所有事情。检查集群状态:
1 | $ redis-cli -c -p 8001 |
测试同上。
总结
手动实现 redis cluster 过程比较繁琐,但是有助于理解 redis cluster 的原理,通过节点握手、分配槽、配置从节点,最终完成了 redis cluster 的搭建。而 redis-trib
则提供了一个简单、易用的脚本以及一系列管理集群的命令,实际应用中正如 redis cluster 的 tutorial 所言,尽管你了解 redis-trib
内部是如何做的,你应该使用 redis-trib
来操作集群。
redis-trib
还提供了一些管理集群的命令,参见文档。