主从复制
为什么使用主从复制
通过持久化功能,Redis保证了即使在服务器重启的情况下也不会丢失(或少量丢失)数据,但是由于数据是存储在一台服务器上的,如果这台服务器出现故障,比如硬盘坏了,也会导致数据丢失。
为了避免单点故障,我们需要将数据复制多份部署在多台不同的服务器上,即使有一台服务器出现故障其他服务器依然可以继续提供服务。
这就要求当一台服务器上的数据更新后,自动将更新的数据同步到其他服务器上,这时候就用到了Redis的主从复制。
主从复制的概念
Redis提供了复制(replication)功能来自动实现多台redis服务器的数据同步我们可以通过部署多台redis,并在配置文件中指定这几台redis之间的主从关系,主负责写入数据,同时把写入的数据实时同步到从机器,这种模式叫做主从复制,即master/slave,并且redis默认master用于写,slave用于读,向slave写数据会导致错误。
模拟主从复制
1.复制三份配置文件,表示三台服务器。
[root@liuqing Lredisconfig]# ls
redis.conf redis79.conf redis80.conf redis81.conf
[root@liuqing Lredisconfig]#
2.修改三份配置文件的内容
-
修改端口【1】
port 6379
【2】port 6380
【3】port 6381
-
修改pid【1】
pidfile /var/run/redis_6379.pid
【2】pidfile /var/run/redis_6380.pid
【3】pidfile /var/run/redis_6381.pid
-
修改日志文件:【1】
logfile "6379.log"
【2】logfile "6380.log"
【3】logfile "6381.log"
-
修改持久化dump.rdb名字【1】
dump6379.rdb
【2】dump6379.rdb
【3】dump6379.rdb
3.启动三台主机。
【1】 info replication 查看主从复制信息,每一台都是主机
127.0.0.1:6379> info replication
# Replication
role:master
connected_slaves:0
master_replid:b59baf68cebb6492b5676cabfc68a8ef2f2f8d5c
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
【2】SLAVEOF host port 设置从机
127.0.0.1:6380> slaveof 127.0.0.1 6379
127.0.0.1:6381> slaveof 127.0.0.1 6379
注意:此处是用命令行来设置从机,一次性的。可以配置文件设置,永久性的。
################################# 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 127.0.0.1 6379
测试结果:
- 主节点设置值,从节点能查看。
- 从节点宕机后重连,从节点能够查看主节点新增的内容。
- 主节点宕机,从节点重新设置主节点后,依旧能查看主节点内容。
- 主节点宕机后,从节点变为主节点
slaveof no one
主从复制原理
1、Slave启动成功连接到master后会发送一个sync命令
2、Master接到命令启动后的存盘进程,同时收集所有接收到的用于修改数据集命令,在后台进程执行完毕之后,master
将传送整个数据文件到slave,以完成一次完全同步;
3、全量复制:而slave服务在数据库文件数据后,将其存盘并加载到内存中;
4、增量复制:Master继续将新的所有收集到的修改命令依次传给slave,完成同步;
5、但是只要是重新连接master,一次完全同步(全量复制)将被自动执行。