开启主从配置

配置主从可以在命令行或配置文件中配置,上面提到主节点负责写,从节点负责读,因此推荐开启从服务器的只读配置,否则的话在从节点的写操作不会同步到主节点会导致数据不一致:

命令行模式

在从服务器命令行中执行下面的命令即可成为该主服务器的从节点:

redis-cli -h 127.0.0.1 -p 6379

#在从服务器执行下面的命令成为或取消成为某节点的从节点
#slaveof  主服务器的IP  端口号
#slaveof  host port
slaveof 192.168.3.67 6379

#取消成为任何服务器的从服务器
slaveof no one

#从服务器只读(推荐配置)
config set slave-read-only yes

#查看主从信息
info replication

#配置主节点ACL账号密码(Redis6开启ACL的情况)
config set masteruser username
config set masterauth password

slaveof 命令是异步的,不会阻塞。
同时,从服务器现有的数据会先被清空,然后才会同步主服务器的数据。

配置文件

在从服务器配置文件中添加下面的配置然后重启从服务器即可:

#在从节点配置文件中新增下面两个配置即可指定成为某个主节点的从节点

################################# REPLICATION #################################

# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
#   +------------------+      +---------------+
#   |      Master      | ---> |    Replica    |
#   | (receive writes) |      |  (exact copy) |
#   +------------------+      +---------------+
#
# 1) Redis replication is asynchronous, but you can configure a master to
#    stop accepting writes if it appears to be not connected with at least
#    a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
#    master if the replication link is lost for a relatively small amount of
#    time. You may want to configure the replication backlog size (see the next
#    sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
#    network partition replicas automatically try to reconnect to masters
#    and resynchronize with them.
#
# replicaof <masterip> <masterport>
replicaof 192.168.3.67 6379

# If the master is password protected (using the "requirepass" configuration
# directive below) it is possible to tell the replica to authenticate before
# starting the replication synchronization process, otherwise the master will
# refuse the replica request.
#
# masterauth <master-password>
masterauth xxxx

使用ACL用户同步

上一篇文章中介绍了Redis6的新特性ACL访问控制列表,基于该特性我们可以为Redis设置不同的用户和权限,在主从复制中我们也可以配置该同步用户的账号密码:

#命令行模式
#在从节点配置主节点ACL账号密码(Redis6开启ACL的情况)
config set masteruser default
config set masterauth wyk123456

#在从节点查看主节点的ACL用户密码
config get master*

#配置文件模式 redis.conf
#在从节点配置主节点ACL账号密码(Redis6开启ACL的情况)
masteruser default
masterauth wyk123456

作者:Jeebiz  创建时间:2023-01-13 22:56
最后编辑:Jeebiz  更新时间:2024-08-16 11:14