redis主从复制与高可用

时间:2021-07-11 06:52:36

一:redis分布式及高可用

一:redis主从复制

原理:

第一次开启
1. 从服务器向主服务器发送 SYNC 命令。
2. 接到 SYNC 命令的主服务器会调用BGSAVE 命令,创建一个 RDB 文件,并使用缓冲区记录接下来执行的所有写命令。
3. 当主服务器执行完 BGSAVE 命令时,它会向从服务器发送 RDB 文件,而从服务器则会接收并载入这个文件。

之后不需要从服务器向主服务器请求,主会自动向从发送
4. 主服务器将缓冲区储存的所有写命令(广播形式)发送给从服务器执行。

 

二:主从复制实现

1、环境:
准备两个或两个以上redis实例

mkdir /data/638{0..2}

配置文件示例:
cat >> /data/6380/redis.conf << EOF
port 6380
daemonize yes
pidfile /data/6380/redis.pid
loglevel notice
logfile "/data/6380/redis.log"
dbfilename dump.rdb
dir /data/6380
requirepass 123
masterauth 123
EOF

cp /data/6380/redis.conf /data/6381/redis.conf
cp /data/6380/redis.conf /data/6382/redis.conf

sed -i 's#6380#6381#g' /data/6381/redis.conf
sed -i 's#6380#6382#g' /data/6382/redis.conf


启动:
redis-server /data/6380/redis.conf
redis-server /data/6381/redis.conf
redis-server /data/6382/redis.conf

netstat -lnp|grep 638


主节点:6380
从节点:6381、6382


2、开启主从:
6381/6382命令行:

redis-cli -p 6381 -a 123 SLAVEOF 127.0.0.1 6380
redis-cli -p 6382 -a 123 SLAVEOF 127.0.0.1 6380


3、查询主从状态
redis-cli -p 6380 -a 123 info replication
redis-cli -p 6381 -a 123 info replication
redis-cli -p 6382 -a 123 info replication

 

三:redis高可用

redis-sentinel(哨兵) redis自带的功能,一个节点宕了自动切换主,类似mysql中高可用产品MHA

功能:
1、监控
2、自动选主,切换(6381 slaveof no one)
3、2号从库(6382)指向新主库(6381)
4、应用透明

-------------
sentinel搭建过程

mkdir /data/26380
cd /data/26380

cat >> sentinel.conf << EOF
port 26380
dir "/data/26380"
sentinel monitor mymaster 127.0.0.1 6380 1
sentinel down-after-milliseconds mymaster 5000
sentinel auth-pass mymaster 123
EOF

启动:
redis-sentinel /data/26380/sentinel.conf &

==============================
如果有问题:
1、重新准备1主2从环境
2、kill掉sentinel进程
3、删除sentinel目录下的所有文件
4、重新搭建sentinel
======================================

停主库测试:

[root@db01 ~]# redis-cli -p 6380 shutdown

[root@db01 ~]# redis-cli -p 6381 info replication

启动源主库(6380),看状态。