Redis集群在保证主从加哨兵的基本功能之外,还能够提升Redis存储数据的能力。
一致性hash环
k1-->crc(16)===? 0-16384
redis集群的ping-pang机制:一个主机向另一个主机ping,另一个pang回来,说明连接成功,通过这样的方式判断redis是否宕机,如果ping了没有pang回来,不一定是它坏了,也有可能是你坏了。
redis主机宕机后,从机可以上位
集群默认分配16384个hash槽,如果有三个主节点,则每个阶段对应0-5000,5000-10000,1000-15000
有四个主节点 ,对应你 0-4000 4000-8000 8000-12000 12000-16000
存取数据是对key进行crc16算法,对16384取余,余数在那个范围里就在那个redis里面存。
Redis集群选举原理
集群配置
新建 /usr/local/docker/redis/cluster 目录 目录下新建 conf 目录 conf目录下新建redis1-6.conf文件
下图是文件的内容
# redis.conf
# 指定redis的端口号
port 7001
# 开启Redis集群
cluster-enabled yes
# 集群信息的文件
cluster-config-file nodes-7001.conf
# 集群的对外ip地址
cluster-announce-ip 192.168.59.12
# 集群的对外port
cluster-announce-port 7001
# 集群的总线端口
cluster-announce-bus-port 17001
redis1-6.conf的ip地址都一样,是宿主主机地址,但是总线端口,对外port,集群信息文件,port改为对应的123456.
docker-compose.yml文件如下:
# docker-compose.yml
version: "3.1"
services:
redis1:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis1
environment:
- TZ=Asia/Shanghai
ports:
- 7001:7001
- 17001:17001
volumes:
- ./conf/redis1.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
redis2:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis2
environment:
- TZ=Asia/Shanghai
ports:
- 7002:7002
- 17002:17002
volumes:
- ./conf/redis2.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
redis3:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis3
environment:
- TZ=Asia/Shanghai
ports:
- 7003:7003
- 17003:17003
volumes:
- ./conf/redis3.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
redis4:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis4
environment:
- TZ=Asia/Shanghai
ports:
- 7004:7004
- 17004:17004
volumes:
- ./conf/redis4.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
redis5:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis5
environment:
- TZ=Asia/Shanghai
ports:
- 7005:7005
- 17005:17005
volumes:
- ./conf/redis5.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
redis6:
image: daocloud.io/library/redis:5.0.7
restart: always
container_name: redis6
environment:
- TZ=Asia/Shanghai
ports:
- 7006:7006
- 17006:17006
volumes:
- ./conf/redis6.conf:/usr/local/redis/redis.conf
command: ["redis-server","/usr/local/redis/redis.conf"]
docker-compose up -d 运行
启动了6个Redis的节点。
随便跳转到一个容器内部,使用redis-cli管理集群
在容器内部输入一下命令,6台reids对应的ip加端口
redis-cli --cluster create 192.168.59.12:7001 192.168.59.12:7002 192.168.59.12:7003 192.168.59.12:7004 192.168.59.12:7005 192.168.59.12:7006 --cluster-replicas 1
显示以下信息,点yes
输入命令 redis-cli -h 192.168.59.12 -p 7001 -c 连接 输入7001端口,存到7003里面了,就是通过算法算的
redis-cli连不上