redis 非集群的主从配置及切换
单纯的master-slave不能称之为集群,只能叫做读写分离。此案例只针对master为单点服务,且程序端写死master为可写,slave为只读。若master宕机则不可用,若主从未开启持久化,不要立刻重启master否则会flush掉slave的数据。此方案适用于master需要停机而不让内存的数据丢失。
若集群为高可用方案如sentinel,则无需手动切换,sentinel自动触发故障转移,无需客户端触发操作。
环境描述:
主redis:119.29.36.237 6379
主redis:119.29.36.237 6380
一、主从配置
1、将主从redis配置文件redis.conf中的aemonize no 改为 yes
daemonize yes
pidfile /var/run/redis_6379.pid
port 6379
dir /var/redis/6379
2、修改从redis配置文件redis.conf中的port 6379 改为 6380,添加slaveof 119.29.36.237 6379
daemonize yes
slaveof 119.29.36.237 6379
pidfile /var/run/redis_6380.pid
port 6380
创建文件 mkdir -p /var/redis/6379 /var/redis-slave/6380
3、启动主从服务
主redis:
redis-server /etc/redis/6379.conf
从redis:
redis-server /etc/redis/slave.conf
4、测试数据同步
主redis:
redis-cli -p 6379
127.0.0.1:6379> KEYS *
(empty list or set)
127.0.0.1:6379> set name bat
OK
127.0.0.1:6379> get name
"bat"
从redis:
redis-cli -h 127.0.0.1 -p 6380
127.0.0.1:6380> get name
"bat"
5、默认是读写分离的
在从redis:
127.0.0.1:6380> set car bmw
(error) READONLY You can't write against a read only slave.
二、主从切换
1、停止主redis
#ps aux |grep redis
root 2931 0.0 0.1 35088 1816 ? Ssl 11:05 0:00 redis-server *:6379
root 2937 0.0 0.1 35088 1808 ? Ssl 11:05 0:00 redis-server *:6380
root 2947 0.0 0.0 10800 968 pts/2 S+ 11:07 0:00 redis-cli -p 6379
root 2951 0.0 0.0 10800 972 pts/0 S+ 11:08 0:00 redis-cli -h 127.0.0.1 -p 6380
root 2956 0.0 0.0 5504 724 pts/3 S+ 11:09 0:00 grep redis
#kill 2931
#redis-cli -p 6379
Could not connect to Redis at 127.0.0.1:6379: Connection refused
2、将在从上将从redis设成主redis
# redis-cli -p 6380 slaveof NO ONE
OK
3、测试从redis是否切换从主redis
#redis-cli -p 6380
127.0.0.1:6380> KEYS *
1) "name"
127.0.0.1:6380> get name
"bat"
127.0.0.1:6380> set car bmw
OK
127.0.0.1:6380> set person man
OK
127.0.0.1:6380> kEYS *
1) "name"
2) "person"
3) "car"
4、原来的主redis恢复正常了,要重新切换回去
1)将现在的主redis的数据进行保存
#redis-cli -p 6380
127.0.0.1:6380> KEYS *
1) "name"
2) "person"
3) "car"
127.0.0.1:6380> save
OK
2)将现在的主redis根目录下dump.rdb文件拷贝覆盖到原来主redis的根目录
cp /var/redis-slave/6380/dump.rdb /var/redis/6379/
cp: overwrite `/var/redis/6379/dump.rdb'? y
3)启动原来的主redis
redis-server /etc/redis/6379.conf
4)在现在的主redis中切换
# redis-cli -p 6380 slaveof 119.29.36.237 6379
OK
测试是否切换成功
主
redis-cli -p 6379
127.0.0.1:6379> KEYS *
1) "person"
2) "car"
3) "name"
127.0.0.1:6379> set test master
OK
127.0.0.1:6379> KEYS *
1) "person"
2) "car"
3) "name"
4) "test"
从
127.0.0.1:6380> kEYS *
1) "test"
2) "name"
3) "car"
4) "person"
127.0.0.1:6380> set test slave
(error) READONLY You can't write against a read only slave.