Redis主从复制
是什么
主机数据更新后根据配置和策略, 自动同步到备机的master/slaver机制,Master以写为主,Slave以读为主。
能干吗
读写分离,性能扩展
容灾快速恢复
实现
此处我为一主双从,也就是三台服务器
- 拷贝多个redis.conf文件并改名(例:redis6379.conf)
修改里面配置
pidfile /var/run/redis_6379.pid(291行)
port 6379(98行)
dbfilename dump6379.rdb(433行)
配置了密码的话需要加改一行(这一行原先是注释的,需要放开)
masterauth "密码"(486行)
另外两台从机同上,但是端口号要不相同
- 启动服务器
./redis-server /myredis/redis6379.conf
./redis-server /myredis/redis6380.conf
./redis-server /myredis/redis6381.conf
- 进入客户端
/usr/local/bin/redis-cli -p 端口号
- 查看三台主机运行情况
info replication #打印主从复制的相关信息
127.0.0.1:6379> info replication
NOAUTH Authentication required.
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379> info replication
role:master
connected_slaves:0
master_failover_state:no-failover
master_replid:fbd16328dcd4296f8347b0b15934aced272f01b3
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
- 其他两台同上
- 配置从库
slaveof <ip><port> 成为某个实例的从服务器
# 例:slaveof localhost 6379
哨兵模式
是什么
能够后台监控主机是否故障,如果故障了根据投票数自动将从库转换为主库。
怎么玩
调整为一主二仆的模式(6379带着6380,6381),即6379是主机,其他两台是6379的从机
- 自定义的/myredis目录下新建sentinel.conf文件,名字绝不能错
- 配置哨兵,填写内容
sentinel monitor mymaster 127.0.0.1 6379 1
#其中mymaster为监控对象起的服务器名称, 1 为至少有多少个哨兵同意迁移的数量。
sentinel auth-pass mymaster 123123
# 如果要有密码,需配置密码
sentinel failover-timeout mymaster 20000
# 设置时间
- 启动哨兵
# /usr/local/bin/redis-sentinel /myredis/sentinel.conf
416739:X 19 Oct 2022 21:56:09.750 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
416739:X 19 Oct 2022 21:56:09.750 # Redis version=6.2.7, bits=64, commit=00000000, modified=0, pid=416739, just started
416739:X 19 Oct 2022 21:56:09.750 # Configuration loaded
416739:X 19 Oct 2022 21:56:09.750 * monotonic clock: POSIX clock_gettime
416739:X 19 Oct 2022 21:56:09.750 # A key '__redis__compare_helper' was added to Lua globals which is not on the globals allow list nor listed on the deny list.
_._
_.-``__ ''-._
_.-`` `. `_. ''-._ Redis 6.2.7 (00000000/0) 64 bit
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, ) Running in sentinel mode
|`-._`-...-` __...-.``-._|'` _.-'| Port: 26379
| `-._ `._ / _.-' | PID: 416739
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' | https://redis.io
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'
`-.__.-'
416739:X 19 Oct 2022 21:56:09.754 # Sentinel ID is a58b60c40d7efd988a548f5f23995a15cedf8e16
416739:X 19 Oct 2022 21:56:09.754 # +monitor master mymaster 127.0.0.1 6379 quorum 1
416739:X 19 Oct 2022 21:56:09.754 * +slave slave 127.0.0.1:6380 127.0.0.1 6380 @ mymaster 127.0.0.1 6379
416739:X 19 Oct 2022 21:56:09.757 * +slave slave 127.0.0.1:6381 127.0.0.1 6381 @ mymaster 127.0.0.1 6379
效果:当主机挂掉,会从从机中选举产生新的主机