1 是什么
主机数据更新后根据配置和策略,自动同步到备机的master/slaver机制,Master以写为主,Slave以读为主
2 怎么用
a) 配从(库)不配主(库)
b) 从库配置:slaveof 主库IP 主库端口
Ⅰ) 每次与master断开之后,都需要重新连接,除非你配置进redis.conf文件
Ⅱ) info replication
c) 修改配置文件细节操作
Ⅰ) 拷贝多个redis.conf文件
Ⅱ) 开启daemonize yes
Ⅲ) pid文件名字-----eg:pidfile "/var/run/redis_6379.pid"
Ⅳ) 指定端口--------eg:port 6379
Ⅴ) log文件名字-----eg:logfile "6379.log"
Ⅵ) dump.rdb名字----eg:dbfilename "dump6379.rdb"
d) 根据不同的配置文件,启动不同端口的Redis
[root@root src]# ./redis-server ../../myRedis/redis6381.conf
[root@root src]# ./redis-cli -p 6381




3 开始
a) 分别在三个端口输入命令:info replication,可以看到3个Redis都是master

b) 在6379,设置key与value

c) 在6380,执行命令同步:SLAVEOF 127.0.0.1 6379,此时会将6379下的key同步到6380,且6380的角色会有master自动转为slave,
且此时查看6379会看到6380作为从的信息



d) 此时,在6379设置新的key,会自动同步到6380上


e) 在从机上不能进行写操作

f) 当主机关闭或因某种原因停止Redis服务时,从机会一直等待主机,直到主机重新启动




g) 当从机因某些原因与master断开之后,都需要重新连接,除非你配置进redis.conf文件

h) 上一个Slave可以是下一个slave的Master,Slave同样可以接收其他slaves的连接和同步请求,那么该slave作为了链条中下一个的master,
可以有效减轻master的写压力


i) 当主机关闭或因某种原因停止Redis服务时,在从机执行slaveof no one,会将改从机转换为主机


4 复制原理
a) slave启动成功连接到master后会发送一个同步(sync)命令
b) Master接到命令启动后台的存盘进程,同时收集所有接收到的用于修改数据集命令, 在后台进程执行完毕之后,master将传送整个数据文件到slave,以完成一次完全同步
c) 全量复制:而slave服务在接收到数据库文件数据后,将其存盘并加载到内存中。
d) 增量复制:Master继续将新的所有收集到的修改命令依次传给slave,完成同步
e) 但是只要是重新连接master,一次完全同步(全量复制)将被自动执行
5 哨兵模式:能够后台监控主机是否故障,如果故障了根据投票数自动将从库转换为主库
a) 配置文件:sentinel.conf
```
# sentinel monitor 被监控数据库名字 IP地址 端口号 最后一个数字1,表示主机挂掉后salve投票看让谁接替成为主机,得票数多少后成为主机
sentinel monitor host6379 127.0.0.1 6379 1
#可以监控多个master
# sentinel monitor host6379 127.0.0.2 6379 1
```

b) 将6380和6381切回成6379的从机







6 主从复制的缺点
由于所有的写操作都是先在Master上操作,然后同步更新到Slave上,所以从Master同步到Slave机器有一定的延迟,当系统很繁忙的时候,延迟问题会更加严重,Slave机器数量的增加也会使这个问题更加严重。
网友评论