1,版本.均为yum安装.
[root@226-129 ~]# redis-server --version
Redis server version 2.4.10 (00000000:0)
[root@226-129 ~]# redis-cli --version
redis-cli 2.4.10
[root@226-129 ~]# keepalived --version
Keepalived v1.2.13 (03/19,2015)
2,配置文件内容注意事项.
a,要实现redis主从复制,从节点配置文件里添加一行slaveof 172.16.226.129(主节点ip) 6379(主节点端口).
b,keepalived配置文件内容:
vrrp_script chk_redis {
script "/etc/keepalived/scripts/redis_check.sh" ###监控脚本
interval 2 ###监控时间
}
vrrp_instance VI_1 {
state MASTER ###设置为MASTER
interface eth0 ###监控网卡
virtual_router_id 51
priority 101 ###权重值
authentication {
auth_type PASS ###加密
auth_pass redis ###密码
}
track_script {
chk_redis ###执行上面定义的chk_redis
}
virtual_ipaddress {
172.16.226.108 ###VIP
}
notify_master /etc/keepalived/scripts/redis_master.sh
notify_backup /etc/keepalived/scripts/redis_backup.sh
notify_fault /etc/keepalived/scripts/redis_fault.sh
notify_stop /etc/keepalived/scripts/redis_stop.sh
}
从节点只需要将权重值设的小一点即可.
3,实现redis主从转换的脚本:
[root@226-129 keepalived]# cat scripts/redis_master.sh
#!/bin/bash
REDISCLI="/usr/bin/redis-cli"
LOGFILE="/var/log/keepalived-redis-state.log"
echo "[master]" >> $LOGFILE
date >> $LOGFILE
echo "Being master...." >> $LOGFILE 2>&1
echo "Run SLAVEOF cmd ..." >> $LOGFILE
$REDISCLI SLAVEOF 192.168.241.35 6379 >> $LOGFILE 2>&1
sleep 10 #延迟10秒以后待数据同步完成后再取消同步状态
echo "Run SLAVEOF NO ONE cmd ..." >> $LOGFILE
$REDISCLI SLAVEOF NO ONE >> $LOGFILE 2>&1
[root@226-129 keepalived]# cat scripts/redis_check.sh
#!/bin/bash
ALIVE=`/usr/bin/redis-cli PING`
if [ "$ALIVE" == "PONG" ]; then
echo $ALIVE
exit 0
else
echo $ALIVE
exit 1
fi
[root@226-129 keepalived]# cat scripts/redis_backup.sh
#!/bin/bash
REDISCLI="/usr/bin/redis-cli"
LOGFILE="/var/log/keepalived-redis-state.log"
echo "[backup]" >> $LOGFILE
date >> $LOGFILE
echo "Being slave...." >> $LOGFILE 2>&1
sleep 15 #延迟15秒待数据被对方同步完成之后再切换主从角色
echo "Run SLAVEOF cmd ..." >> $LOGFILE
$REDISCLI SLAVEOF 192.168.241.35(另外一个节点的ip) 6379 >> $LOGFILE 2>&1
[root@226-129 keepalived]# cat scripts/redis_fault.sh
#!/bin/bash
LOGFILE=/var/log/keepalived-redis-state.log
echo "[fault]" >> $LOGFILE
date >> $LOGFILE
[root@226-129 keepalived]# cat scripts/redis_stop.sh
#!/bin/bash
LOGFILE=/var/log/keepalived-redis-state.log
echo "[stop]" >> $LOGFILE
date >> $LOGFILE
给脚本以执行权限.
测试:略
远程链接redis: redis-cli -h 172.16.226.108(服务器ip) -p 6379(服务端口)
本文出自 “linux笔记” 博客,请务必保留此出处http://lsfeng.blog.51cto.com/7959286/1718331
原文地址:http://lsfeng.blog.51cto.com/7959286/1718331