1.redis-cluster架构图
架构细节:
(1)所有的redis节点彼此互联(PING-PONG机制),内部使用二进制协议优化传输速度和带宽.
(2)节点的fail是通过集群中超过半数的节点检测失效时才生效.
(3)客户端与redis节点直连,不需要中间proxy层.客户端不需要连接集群所有节点,连接集群中任何一个可用节点即可
(4)redis-cluster把所有的物理节点映射到[0-16383]slot上,cluster 负责维护node<->slot<->value
Redis 集群中内置了 16384 个哈希槽,当需要在 Redis 集群中放置一个 key-value 时,redis 先对 key 使用 crc16 算法算出一个结果,然后把结果对 16384 求余数,这样每个 key 都会对应一个编号在 0-16383 之间的哈希槽,redis 会根据节点数量大致均等的将哈希槽映射到不同的节点
示例如下:
2.redis-cluster投票:容错
(1)集群中所有master参与投票,如果半数以上master节点与其中一个master节点通信超过(cluster-node-timeout),认为该master节点挂掉.
(2):什么时候整个集群不可用(cluster_state:fail)
如果集群任意master挂掉,且当前master没有slave,则集群进入fail状态。也可以理解成集群的[0-16383]slot映射不完全时进入fail状态。如果集群超过半数以上master挂掉,无论是否有slave,集群进入fail状态。
3.搭建Ruby环境
redis集群管理工具redis-trib.rb依赖ruby环境,首先需要安装ruby环境。
1)安装ruby
[root@localhost bin]#yum install ruby
[root@localhost bin]#yum install rubygems
2)使用sftp工具上传redis-4.0.0.gem至/java下
3)安装ruby和redis的接口程序
[root@localhost java]#gem install redis-4.0.0.gem
4)将Redis集群搭建脚本文件复制到/opt/java/redis-cluster目录下
[root@localhost /]# cd /java/redis-4.0.0/src/
[root@localhost src]# ll *.rb
-rwxrwxr-x. 1 root root 48141 4月 1 2015 redis-trib.rb
[root@localhost src]# cp redis-trib.rb /opt/java/redis-cluster/ -r
4.集群的搭建过程
搭建集群最少也得需要3台主机,如果每台主机再配置一台从机的话,则最少需要6台机器。
1)创建6个redis实例,需要端口号7001~7006,复制出一个7001机器
[root@localhost redis]# cp bin ../redis-cluster/7001 -r
2)如果存在持久化文件,则删除
[root@localhost 7001]# rm -rf appendonly.aof dump.rdb
3)设置集群参数和修改端口
4)复制出7002-7006机器,然后修改7002-7006机器的端口
[root@localhost redis-cluster]# cp 7001/ 7002 -r
[root@localhost redis-cluster]# cp 7001/ 7003 -r
[root@localhost redis-cluster]# cp 7001/ 7004 -r
[root@localhost redis-cluster]# cp 7001/ 7005 -r
[root@localhost redis-cluster]# cp 7001/ 7006 -r
5)启动7001-7006这六台机器
[root@localhost redis-cluster]# vi start.sh
cd 7001
./redis-server redis.conf
cd ..
cd 7002
./redis-server redis.conf
cd ..
cd 7003
./redis-server redis.conf
cd ..
cd 7004
./redis-server redis.conf
cd ..
cd 7005
./redis-server redis.conf
cd ..
cd 7006
./redis-server redis.conf
cd ..
[root@localhost redis-cluster]# chmod 777 start.sh
[root@localhost redis-cluster]# ./start.sh
[root@localhost redis-cluster]# ps -ef|grep redis
root 3750 3677 0 20:52 pts/2 00:00:00 cp -i redis-trib.rb /opt/java/redis-cluster
root 3779 3677 0 20:54</