Redis分片集群配置——Cluster模式

493 阅读3分钟

Redis集群有多种模式,包括主从模式、Sentinel(哨兵)模式、Cluster模式等。

Redis最先是使用主从模式做集群,在该模式中,如果master宕机则需要手动将slave配置为master。

基于以上缺点,Redis提出了哨兵模式,该模式使用哨兵机制来监视master的存活情况,如果master宕机,哨兵机制会自动进行master的选举和切换。

哨兵机制的缺点是不能动态扩充空间,所以Redis在3.x版本提出了Cluster集群模式。本文主要讲解的就是Cluster模式的配置和各种操作。

Cluster模式介绍

Cluster模式也称为Redis-Cluster集群,采用无中心结构,每个节点保存部分数据和整个集群的状态信息,每个节点都有与其他节点的连接。

Cluster集群通过分区来提供一定程度的可用性,即就算集群中有一部分节点失效或者无法进行通讯,集群也可以继续处理命令请求。

Cluster集群配置

1. 配置多个Redis实例

为了保证配置文件的容错性,我将在拷贝的配置文件中进行操作。

> mkdir /usr/local/redis/redis_cluster
# 将redis.conf文件复制到指定目录,并重命名为redis_6379.conf
> cp /opt/Redis-6.2.3/conf/redis.conf /usr/local/redis/redis_cluster/redis_6379.conf

(1)将redis_6379.conf文件中的指定属性修改为指定值:

daemonize属性指定Redis是否以守护线程的方式启动,默认为no。

daemonize yes:表示开启守护线程模式,在该模式下,Redis会在后台运行,并将进程pid写入到配置文件选项pidfile设置的路径文件中,此时Redis将持续运行,直到手动kill该进程或执行shutdown命令。

daemonize no:表示不开启守护线程模式,在该模式下,当前界面将进入Redis的命令行界面(Redis-cli),执行exit或关闭连接工具(XShell等)操作都会导致Redis进程退出。

daemonize yes

Redis的默认端口号

port 6379

配置pid的存储路径

pidfile "/var/run/redis_6379.pid"

重命名RDB文件

dbfilename "dump6379.rdb"

集群目录的路径,多个Rredis实例将存放在这个目录下

dir "/usr/local/soft/redis6/redis_cluster"

日志文件的输出目录

logfile "/集群配置的路径/redis_cluster/redis_err_6379.log"

开启Cluster集群

cluster-enabled yes

保存集群节点信息的文件,存放在集群目录下

cluster-config-file nodes-6379.conf

集群节点失效超时时间

cluster-node-timeout 15000

(2)拷贝多个实例

因为一个集群至少要有3个主节点,所以我们以6个节点为例。先拷贝出6个Redis配置文件:

[root@localhost redis_cluster]# cp redis_6379.conf redis_6380.conf
[root@localhost redis_cluster]# cp redis_6379.conf redis_6381.conf
[root@localhost redis_cluster]# cp redis_6379.conf redis_6389.conf
[root@localhost redis_cluster]# cp redis_6379.conf redis_6390.conf
[root@localhost redis_cluster]# cp redis_6379.conf redis_6391.conf

修改配置文件,使用vim的查找替换操作:

#打开文件
vim redis_6380.conf
#将该文件中所有的“6379”替换为“6380”
:s%/6379/6380

2. 启动Redis实例

(1)按照以下步骤分别启动多个Redis实例

[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6379.conf
[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6380.conf
[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6381.conf
[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6389.conf
[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6390.conf
[root@localhost redis_cluster]# redis-server /usr/local/soft/redis6/redis_cluster/redis_6391.conf

(2)启动实例后,检查相应的nodes-xxxx.conf文件是否生成(xxxx为端口号)

image.png

3. 配置集群

(1)将集群配置成三组一主一从的组合

[root@localhost redis6]# redis-cli --cluster create --cluster-replicas 1 192.168.43.2:6379 192.168.43.2:6380 192.168.43.2:6381 192.168.43.2:6389 192.168.43.2:63790 192.168.43.2:6391
# -replicas 1 表示一个master对应一个slave

执行命令后,有以下提示:

image.png

输入“yes”后回车:

image.png

(2)以集群方式登录Redis

image.png

(3)查看集群信息

10.6.207.225:6379> cluster nodes

image.png

至此,集群搭配完成。