集群版本和环境
Redis集群要求至少3个主节点3个从节点,共计6个节点。
操作系统 CentOS 7.4
Redis版本 6.0.5
主节点
192.168.239.143 7000
192.168.239.147 7000
192.168.239.149 7000
从节点
192.168.239.143 7001
192.168.239.147 7001
192.168.239.149 7001
修改系统配置
关闭NetworkManager
[root@localhost ~]# systemctl disable NetworkManager --关闭自启动
[root@localhost ~]# systemctl stop NetworkManager
[root@localhost ~]# systemctl status NetworkManager
关闭防火墙
systemctl stop firewalld.service
systemctl disable firewalld.service --关闭自启动
firewall-cmd --state
vi /etc/selinux/config
SELINUX=disabled
安装依赖包
安装gcc套装
yum install -y cpp binutils glibc glibc-kernheaders glibc-common glibc-devel gcc make
升级gcc
yum -y install centos-release-scl
yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++ devtoolset-9-binutils
scl enable devtoolset-9 bash
设置永久升级
echo "source /opt/rh/devtoolset-9/enable" >>/etc/profile
创建Redis节点
1.创建Redis目录并解压
mkdir /redis
tar xzf redis-6.0.5.tar.gz
2.安装Redis
cd /redis/redis-6.0.5
make install
3.创建节点目录
cd /redis/redis-6.0.5
mkdir cluster
cd cluster
mkdir 7000 7001
4.修改Redis配置文件
以192.168.239.143为例,其他节点步骤相同
将配置文件拷贝到创建好的端口文件夹下
cp /redis/redis-6.0.5/redis.config /redis/redis-6.0.5/cluster/7000
cp /redis/redis-6.0.5/redis.config /redis/redis-6.0.5/cluster/7001
每个节点的主从节点都需要配置文件
主:
port 7000
bind 192.168.239.143
cluster-enabled yes
cluster-config-file nodes_7000.conf
cluster-node-timeout 5000
appendonly yes
daemonize yes
logfile "/redis/redis-6.0.5/cluster/redis_7000.log"
pidfile /var/run/redis_7000.pid
从:
port 7001
bind 192.168.239.143
cluster-enabled yes
cluster-config-file nodes_7001.conf
cluster-node-timeout 5000
appendonly yes
daemonize yes
logfile "/redis/redis-6.0.5/cluster/redis_7001.log"
pidfile /var/run/redis_7001.pid
5.启动Redis节点服务
redis-server /redis/redis-6.0.5/cluster/7000/redis.conf
redis-server /redis/redis-6.0.5/cluster/7001/redis.conf
创建Redis集群
目前为止,我们已经创建了Redis节点并且启动服务,接下来就要创建Redis集群了。在Redis 6中,使用redis-cli命令来创建,其中--cluster-replicas 1的意思是每个主节点需要1个从节点。
例如:
redis-cli --cluster create 192.168.239.143:7000 192.168.239.147:7000 \
192.168.239.149:7000 192.168.239.143:7001 192.168.239.147:7001 \
192.168.239.149:7001 --cluster-replicas 1
我们最初的目标是创建3个主节点加3个从节点的集群,显然这条命令并没有指定哪些主哪些是从,其实在执行后,Redis会建议主从节点的分配,M表示主(Master)节点,S表示从(Slave)节点,你只要选择yes即可。
验证Redis集群
redis-cli -c -h 192.168.239.143 -p 7000
192.168.239.143:7000> set foo bar
-> Redirected to slot [12182] located at 192.168.239.147:7000
OK
192.168.239.147:7000> set hello world
-> Redirected to slot [866] located at 192.168.211.143:7000
OK
192.168.211.143:7000> get foo
-> Redirected to slot [12182] located at 192.168.239.147:7000
"bar"
192.168.239.147:7000> get hello
-> Redirected to slot [866] located at 192.168.211.143:7000
"world"
从结果可以看出来,创建的键被分配到了不同节点的slots中,说明了集群运行正常。