redis一主二从+三哨兵配置
场景:一台服务上搭建redis主从复制
前提:服务器上的redis是通过宝塔安装的,安装路径为/www/server/redis/
1. cd /www/server/redis && cp redis.conf redis_6380.conf
2. vim redis_6380.conf 更改以下几项:
pidfile /var/run/redis_6380.pid
port 6380
dbfilename dump_6380.rdb
3. cd /www/server/redis && cp start.pl start_6380.pl
4. 设置启动脚本 cd /etc/init.d && cp redis redis-6380
5. vim redis-6380 内容如下:
#!/bin/sh
# chkconfig: 2345 56 26
# description: Redis Service
# Provides: Redis
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts Redis
# Description: starts the BT-Web
# Simple Redis init.d script conceived to work on Linux systems
# as it does use of the /proc filesystem.
CONF="/www/server/redis/redis_6380.conf"
REDIS_PORT=$(cat $CONF |grep port|grep -v '#'|awk '{print $2}')
if [ "$REDIS_PASS" != "" ];then
REDIS_PASS=" -a $REDIS_PASS"
fi
if [ -f "/www/server/redis/start_6380.pl" ];then
STAR_PORT=$(cat /www/server/redis/start_6380.pl)
else
STAR_PORT="6380"
fi
EXEC=/www/server/redis/src/redis-server
PIDFILE=/var/run/redis_6380.pid
redis_start(){
echo "Starting Redis server..."
nohup sudo -u redis $EXEC $CONF >> /www/server/redis/logs.pl 2>&1 &
echo ${REDIS_PORT} > /www/server/redis/start_6380.pl
sleep 1.5
if [ "${REDIS_PID}" ]; then
echo "${REDIS_PID}" > ${PIDFILE}
fi
}
redis_status(){
if [ "${REDIS_PID}" ]; then
echo "redis is running..."
else
echo "redis is stopped..."
fi
}
redis_stop(){
if [ "${REDIS_PID}" ]; then
echo "${REDIS_PID}" > ${PIDFILE}
fi
}
redis_status(){
REDIS_PID=$(ps -ef|grep redis-server|grep -v "grep"|grep -v "root"|awk '{print $2}')
if [ "${REDIS_PID}" ]; then
echo "redis is running..."
else
echo "redis is stopped..."
fi
}
redis_stop(){
echo "Stopping ..."
$CLIEXEC shutdown
sleep 1
pkill -9 redis-server
rm -f ${PIDFILE}
echo "Redis stopped"
}
case "$1" in
start)
redis_start
;;
stop)
redis_stop
;;
status)
redis_status
;;
restart|reload)
redis_stop
sleep 0.3
redis_start
;;
*)
echo "Please use start or stop as first argument"
;;
esac
- 执行
service redis-6380 start
启动另一个redis实例 - 配置主服务器中的redis.conf文件,在redis.conf中添加以下几项:
(1) 将bind 127.0.0.1 注释或改为bind 0.0.0.0
(2) 开启守护进程 daemonize yes
(3) 设置访问密码 requirepass password
(4) 内存策略 maxmemory-policy volatile-lru/allkeys-lru
- 配置从服务中的redis.conf文件,在redis_6380.conf中添加以下几项:
(1) slaveof 192.168.5.22 6379
(2) masterauth password
(3) slave-read-only yes
- 重复上面的步骤再搭建一个端口为6381的redis实例
- 哨兵sentinel.conf文件配置,需要更改以下几项(默认使用redis自带的sentinel.conf):
(1)port 26379 //要跟redis实例的端口区分开
(2)sentinel monitor mymaster 127.0.0.1 6379 2 //master的ip和端口
- 启动哨兵(正确的启动顺序:主-->从-->哨兵)
cd /www/server/redis/ && ./src/redis-sentinel sentinel.conf
- 启动之后进行测试,将redis主服务器下线,看哨兵能否进行故障转移即可