搭建 Redis 主从哨兵模式

[TOC]

一、环境介绍

1.1、介绍

1) 简介无需改配置
2) 配置主从复制黏贴即可,无需很麻烦配置

1.2、主机信息

名称 IP地址 备注
redis 192.168.8.81
redis 192.168.8.82
redis 192.168.8.83

二、搭建 Redis 主从

2.1、部署 Redis 服务

  • 3 台机器依次执行,完成之后即可完成 redis 服务
wget -c http://mirrors.linuxeye.com/oneinstack-full.tar.gz && tar xzf oneinstack-full.tar.gz && ./oneinstack/install.sh --redis  --reboot 

2.2、设置每台机器环境变量

  • 需要每台机器都执行
#   填写 Redis master 机器 ip 地址
redisMasterHost="192.168.8.81"
#   设置 Redis 密码
password="akiraka"
#   获取当前机器 ip 地址
hostsip=$(ip add | egrep -A 3 "enp0s3|eth0|em0" | grep -w inet | awk '{print $2}' | awk -F/ '{print $1}' | tr '.' '.')

2.3、设置每台 Redis 配置

  • 需要每台机器都执行
  • 不建议开启 slave 只读配置,否则重新选举会出问题 [replica-read-only 和 slave-read-only]
cat > /usr/local/redis/etc/redis.conf <<EOF
# 默认不设置的话,redis会响应本机所有可用网卡的连接请求。
# 也可以通过bind配置项来指定要绑定的IP。
bind ${hostsip}
#redis3.2版本后新增protected-mode配置,默认是yes,即开启。设置外部网络连接redis服务,设置方式如下:
# 1、关闭protected-mode模式,此时外部网络可以直接访问
# 2、开启protected-mode保护模式,需配置bind ip或者设置访问密码
protected-mode yes
# Redis 服务端口
port 6379
tcp-backlog 511
# 客户端闲置N秒后关闭连接(0禁用)
timeout 0
# TCP连接保活策略,可以通过tcp-keepalive配置项来进行设置,单位为秒。
# 假如设置为300秒,则server端会每300秒向连接空闲的客户端发起一次ACK请求,
# 以检查客户端是否已经挂掉,对于无响应的客户端则会关闭其连接。
# 如果设置为0,则不会进行保活检测。
tcp-keepalive 300
# 启用后台守护进程运行模式
daemonize yes
supervised no
# pid 路径
pidfile /var/run/redis/redis.pid
# 日志等级
loglevel notice
# redis 日志路径
logfile /usr/local/redis/var/redis.log
# 设置 Redis 数据库数目
databases 16
# 过了900秒并且有1个key发生了改变,触发save动作
# 过了300秒并且有10个key发生了改变,触发save动作
# 过了60秒并且至少有10000个key发生了改变,触发save动作
save 900 1
save 300 10
save 60 10000
# 后台存储错误停止写
stop-writes-on-bgsave-error yes
# 存储至本地数据库时(持久化rdb文件)是否压缩数据
rdbcompression yes
# 存储至本地数据库时(持久化rdb文件)是否压缩数据
rdbchecksum yes
# 持久化rdb存储文件名
dbfilename dump.rdb
# 数据库镜像备份的文件放置的路径
dir /usr/local/redis/var
# 默认不使用diskless同步方式
repl-diskless-sync no
# 无盘复制的延迟默认为5s,是为了等待更多的slave连接
repl-diskless-sync-delay 5
# 主节点打开AOF机制
appendonly yes
# 设置AOF记录的文件名
appendfilename "appendonly.aof"
appendfsync everysec
# 当主进程在进行向磁盘的写操作时,将会阻止其它的fsync调用
no-appendfsync-on-rewrite no
# aof文件触发自动rewrite的百分比,值为0则表示禁用自动rewrite
auto-aof-rewrite-percentage 100
# aof文件触发自动rewrite的最小文件size
auto-aof-rewrite-min-size 128mb
# 是否加载不完整的aof文件来进行启动
aof-load-truncated yes
# 设置lua脚本的最大运行时间,单位为毫秒
lua-time-limit 5000
# redis的slow log是一个系统OS进行的记录查询,它是超过了指定的执行时间的。执行时间不包括类似与client进行交互或发送回复等I/O操作,它只是实际执行指令的时间。
slowlog-log-slower-than 10000
# 设置slowlog的长度,当一个新的命令被记录时,最旧的命令将会从命令记录队列中移除。
slowlog-max-len 128
# 延迟监控,用于记录等于或超过了指定时间的操作,默认是关闭状态,即值为0。
latency-monitor-threshold 0
# 事件通知,默认不启用,具体参数查看配置文件
notify-keyspace-events "Ex"
# 当条目数量较少且最大不会超过给定阀值时,哈希编码将使用一个很高效的内存数据结构,阀值由以下参数来进行配置。
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
# 与哈希类似,少量的lists也会通过一个指定的方式去编码从而节省更多的空间,它的阀值通过以下参数来进行配置。
list-max-ziplist-size -2
list-compress-depth 0
# 集合sets在一种特殊的情况时有指定的编码方式,这种情况是集合由一组10进制的64位有符号整数范围内的数字组成的情况。以下选项可以设置集合使用这种特殊编码方式的size限制。
set-max-intset-entries 512
# 与哈希和列表类似,有序集合也会使用一种特殊的编码方式来节省空间,这种特殊的编码方式只用于这个有序集合的长度和元素均低于以下参数设置的值时。
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
# 设置HyeperLogLog的字节数限制,这个值通常在0~15000之间,默认为3000,基本不超过16000
hll-sparse-max-bytes 3000
# Redis 将会在每秒中抽出10毫秒来对主字典进行重新散列化处理,这有助于尽可能的释放内存
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
# hz默认设为10,提高它的值将会占用更多的cpu,当然相应的redis将会更快的处理同时到期的许多key,以及更精确的去处理超时。
# hz的取值范围是1~500,通常不建议超过100,只有在请求延时非常低的情况下可以将值提升到100。
hz 10

######################################################################################################
# 设置master的认证口令
requirepass ${password}
# 当一个子进程要改写AOF文件,如果以下选项启用,那文件将会在每产生32MB数据时进行同步,这样提交增量文件到磁盘时可以避免出现比较大的延迟。
aof-rewrite-incremental-fsync yes
# 是否启用TCP_NODELAY,如果启用则会使用少量的TCP包和带宽去进行数据传输到slave端,当然速度会比较慢;如果不启用则传输速度比较快,但是会占用比较多的带宽。
repl-disable-tcp-nodelay no
######################################################################################################

############################################# Redis Slave ############################################# 
# slave端的优先级设置,值是一个整数,数字越小表示优先级越高。当master故障时将会按照优先级来选择slave端进行恢复,如果值设置为0,则表示该slave永远不会被选择。
replica-priority 100
# 从节点在处于快照同步期间是否对外提供服务
replica-serve-stale-data yes
# 填写 master 认证口令
masterauth ${password}
############################################# Redis Slave #############################################

# Generated by CONFIG REWRITE
replicaof ${redisMasterHost} 6379
EOF

2.4、重新 Redis 服务

  • 每台机器都需要执行
#   重启 Redis 服务
systemctl restart redis-server

三、查看 Redis 日志

root@aka:~$ tail -f /usr/local/redis/var/redis.log
4090:S 10 Nov 2020 17:23:33.332 * Connecting to MASTER 10.1.12.81:6379
4090:S 10 Nov 2020 17:23:33.332 * MASTER <-> REPLICA sync started
4090:S 10 Nov 2020 17:23:33.333 * Non blocking connect for SYNC fired the event.
4090:S 10 Nov 2020 17:23:33.334 * Master replied to PING, replication can continue...
4090:S 10 Nov 2020 17:23:33.335 * Partial resynchronization not possible (no cached master)
4090:S 10 Nov 2020 17:23:33.336 * Full resync from master: cd4e6d8265650c8afd905b376c48da6ca82f6bc0:56
4090:S 10 Nov 2020 17:23:33.414 * MASTER <-> REPLICA sync: receiving 175 bytes from master
4090:S 10 Nov 2020 17:23:33.414 * MASTER <-> REPLICA sync: Flushing old data
4090:S 10 Nov 2020 17:23:33.414 * MASTER <-> REPLICA sync: Loading DB in memory
4090:S 10 Nov 2020 17:23:33.414 * MASTER <-> REPLICA sync: Finished with success
4090:S 10 Nov 2020 17:23:33.415 * Background append only file rewriting started by pid 4103
4090:S 10 Nov 2020 17:23:33.439 * AOF rewrite child asks to stop sending diffs.
4103:C 10 Nov 2020 17:23:33.439 * Parent agreed to stop sending diffs. Finalizing AOF...
4103:C 10 Nov 2020 17:23:33.439 * Concatenating 0.00 MB of AOF diff received from parent.
4103:C 10 Nov 2020 17:23:33.439 * SYNC append only file rewrite performed
4103:C 10 Nov 2020 17:23:33.439 * AOF rewrite: 4 MB of memory used by copy-on-write
4090:S 10 Nov 2020 17:23:33.532 * Background AOF rewrite terminated with success
4090:S 10 Nov 2020 17:23:33.532 * Residual parent diff successfully flushed to the rewritten AOF (0.00 MB)
4090:S 10 Nov 2020 17:23:33.532 * Background AOF rewrite finished successfully

四、哨兵模式

4.1、添加 sentinel 服务命令

  • 需要每台机器都执行
#   添加启动脚本
cat > /usr/lib/systemd/system/redis-sentinel.service << 'EOF'
[Unit]
Description=Redis sentinel Server
After=network.target

[Service]
Type=forking
User=redis
Group=redis
ExecStart=/usr/local/redis/bin/redis-sentinel /usr/local/redis/etc/sentinel.conf --sentinel
ExecStop=/usr/local/redis/bin/redis-cli -p 26379 shutdown
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 守护进程重新加载
systemctl daemon-reload

4.2、哨兵配置

  • 需要每台机器都执行
cat > /usr/local/redis/etc/sentinel.conf <<EOF
# 保护模式修改为否,允许远程连接
protected-mode no
# 端口
port 26379
# 数据库镜像备份的文件放置的路径
dir "/usr/local/redis/var"
# 哨兵日志路径
logfile "/usr/local/redis/var/sentinel.log"
# 是否以守护进程启动
daemonize yes
# 不允许使用 SENTINEL SET设置n otification-script和 client-reconfig-script。
sentinel deny-scripts-reconfig yes
# 定义Redis主的别名, IP, 端口,这里的2指的是需要至少2个Sentinel认为主Redis挂了才最终会采取下一步行为
sentinel monitor mymaster ${redisMasterHost} 6379 2
# 这里设置了主机多少60000h毫秒无响应,则认为挂了。 
sentinel down-after-milliseconds mymaster 60000 
# 设定120000毫秒内master没有活起来,就重新选举主
sentinel failover-timeout mymaster 120000
# 表示如果master重新选出来后,其它slave节点能同时并行从新master同步缓存的台数有多少个,显然该值越大,所有slave节点完成同步切换的整体速度越快,但如果此时正好有人在访问这些slave,可能造成读取失败,影响面会更广。最保定的设置为1,只同一时间,只能有一台干这件事,这样其它slave还能继续服务,但是所有slave全部完成缓存更新同步的进程将变慢。
sentinel parallel-syncs mymaster 2
# 如果redis配置了密码,那这里必须配置认证,否则不能自动切换, 必须放到 [sentinel monitor] 后面否则启动会报错
sentinel auth-pass mymaster "${password}"
EOF

4.3、修改文件权限

# 权限不修改无法通过命令运行
chown redis:redis /usr/local/redis/etc/sentinel.conf

4.4、开机启动

# 重新加载系统服务
systemctl daemon-reload
# 添加开机启动项
systemctl enable redis-sentinel
# 启动哨兵 
systemctl start redis-sentinel
# 查看启动状态
systemctl status redis-sentinel
# 手动启动
/usr/local/redis/bin/redis-sentinel /usr/local/redis/etc/sentinel.conf --sentinel
# 查看 sentinel
/usr/local/redis/bin/redis-cli -p 26379 info sentinel

4.5、哨兵主从异常

如果当前主是 192.168.8.81 那么哨兵都应该指向 192.168.8.81 地址
如果业务挂了 主跑到 192.168.8.82,但是哨兵配置如果还是 192.168.8.81,此时必须改成 192.168.8.82,否则故障无法漂移
正常来说故障漂移后只要不改哨兵配置即可,但难免会遇到手贱时候

4.6、查看主从状态

redis-cli -h 192.168.8.81 -p 6379 -a "akiraka" info Replication
redis-cli -h 192.168.8.82 -p 6379 -a "akiraka" info Replication
redis-cli -h 192.168.8.83 -p 6379 -a "akiraka" info Replication

1) 查看 redis-01

root@redis-01:$ redis-cli -h 192.168.8.81 -p 6379 -a "akiraka" info Replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:master
connected_slaves:1
slave0:ip=10.1.12.83,port=6379,state=online,offset=10756,lag=0
master_replid:584df052d1c5214c2e416e745a104b1d7f782680
master_replid2:b556b1e9e09df286ccee7f96706d9716f4faf801
master_repl_offset:10756
second_repl_offset:6138
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:10756

2) 查看 redis-02

root@redis-01:$ redis-cli -h 192.168.8.82 -p 6379 -a "akiraka" info Replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:slave
master_host:192.168.8.81
master_port:6379
master_link_status:up
master_last_io_seconds_ago:1
master_sync_in_progress:0
slave_repl_offset:27943
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:5966f6bca287442b61520359454a73ac13377e70
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:27943
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:27943

3) 查看 redis-03

root@redis-02:$ redis-cli -h 192.168.8.83 -p 6379 -a "akiraka" info Replication
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
# Replication
role:slave
master_host:192.168.8.81
master_port:6379
master_link_status:up
master_last_io_seconds_ago:0
master_sync_in_progress:0
slave_repl_offset:29199
slave_priority:100
slave_read_only:1
connected_slaves:0
master_replid:5966f6bca287442b61520359454a73ac13377e70
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:29199
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:29199

4.7、模拟主故障

  • 关闭主master,即可
  • 通过 4.5 命令查看主从是否切换成功
systemctl stop redis-server
systemctl stop redis-sentinel

版权声明:
作者:Akiraka
链接:https://www.akiraka.net/linux/834.html
来源:Akiraka
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
搭建 Redis 主从哨兵模式
[TOC] 一、环境介绍 1.1、介绍 1) 简介无需改配置 2) 配置主从复制黏贴即可,无需很麻烦配置 1.2、主机信息 名称 IP地址 备注 redis 192.168.8.81 主……
<<上一篇
下一篇>>
文章目录
关闭
目 录