1、这里以3台物理机器搭建3主3从为例,分别在3台物理机上面安装redis应用。理论上应该用9台物理机部署9个节点,3主6从,设置min‐replicas‐to‐write参数为1,这种模式下,任一时刻只挂掉一个节点的情况下可以保证数据不丢失和集群的可用性。
参考单机搭建:CentOS7.5安装Redis5.0.9,linux网络优化,redis配置优化
2、修改配置文件:
vi /opt/redis_6379/redis.conf
cluster-enabled yes #开启集群模式
masterauth 123456 #集群模式下必须设置,与requirepass相同
cluster-config-file /opt/redis_6379/nodes.conf #集群节点配置信息,端口号根据实际情况设置
min‐replicas‐to‐write 0 #主节点返回结果前等待多少个从节点成功保存数据,数值应该小于从节点数量
maxmemory 4G #大小根据实际情况设置
3、创建第二个redis实例,修改配置文件,将配置文件中的6379替换成6380:
mkdir -p /opt/redis_6380
cp /opt/redis_6379/redis.conf /opt/redis_6380/redis.conf
vi /opt/redis_6380/redis.conf
3、开放第二个redis实例相关的端口:
firewall-cmd --zone=public --add-port=6380/tcp --permanent
firewall-cmd --zone=public --add-port=16380/tcp --permanent
firewall-cmd --reload
4、修改redis服务启动和停止脚本,同时启动和停止两个redis服务:
vi /etc/init.d/redis
#!/bin/sh
#
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
### BEGIN INIT INFO
# Provides: redis_6379
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Redis data structure server
# Description: Redis data structure server. See https://redis.io
### END INIT INFO
EXEC=/usr/local/bin/redis-server
CLIEXEC=/usr/local/bin/redis-cli
REDISPORTS=(6379 6380) #两台redis的端口
AUTH=123456 #redis密码
for REDISPORT in ${REDISPORTS[*]}
do
PIDFILE=/opt/redis_${REDISPORT}/redis.pid
CONF="/opt/redis_${REDISPORT}/redis.conf"
case "$1" in
start)
if [ -f $PIDFILE ]
then
echo "$PIDFILE exists, process is already running or crashed"
else
echo "Starting Redis server on port ${REDISPORT} ..."
$EXEC $CONF
fi
;;
stop)
if [ ! -f $PIDFILE ]
then
echo "$PIDFILE does not exist, process is not running"
else
PID=$(cat $PIDFILE)
echo "Stopping on port ${REDISPORT} ..."
$CLIEXEC -p $REDISPORT -a $AUTH shutdown
while [ -x /proc/${PID} ]
do
echo "Waiting for Redis to shutdown ..."
sleep 1
done
echo "Redis stopped"
fi
;;
*)
echo "Please use start or stop as first argument"
;;
esac
done
systemctl daemon-reload
5、分别启动6个redis实例,执行命令:
service redis start
6、创建3个master节点:
# -a后面的参数是redis的密码
redis-cli -a 123456 --cluster create 192.168.112.101:6379 192.168.112.102:6379 192.168.112.103:6379
7、查看集群状态:
# -a后面的参数是redis的密码
redis-cli -a 123456 --cluster check 192.168.112.101:6379
8、添加从节点:
#将ip2:6380作为ip1:6379的从节点,ip1:6379的master-id从第七步获取
redis-cli -a 123456 --cluster add-node 192.168.112.102:6380 192.168.112.101:6379 --cluster-slave --cluster-master-id 682217730bbbd2945cc49cea6e43568a56e924ff
#将ip3:6380作为ip2:6379的从节点,ip2:6379的master-id从第七步获取
redis-cli -a 123456 --cluster add-node 192.168.112.103:6380 192.168.112.101:6379 --cluster-slave --cluster-master-id 42d82d2f6864bda4b964fec4da7ced78ac15409e
#将ip1:6380作为ip3:6379的从节点,ip3:6379的master-id从第七步获取
redis-cli -a 123456 --cluster add-node 192.168.112.101:6380 192.168.112.101:6379 --cluster-slave --cluster-master-id 42d82d2f6864bda4b964fec4da7ced78ac15409e
9、测试集群主从同步是否正常