Skip to content

主从复制-搭建一主多从

是什么

主机数据更新后根据配置和策略,自动同步到备机的master/slaver机制,Master以写为主,Slave以读为主

能干嘛

  • 读写分离,性能扩展
  • 容灾快速恢复

怎么玩:主从复制

复制公共的redis.conf(就是原来的redis.conf)

shell
cp /etc/redis.conf .

开启持久化RDB,关闭AOF

shell
daemonize yes #RDB开启
appendonly no #关闭AOF

新建一主二从配置文件


redis6379.conf

shell
#引入公共配置
include /myredis/redis.conf    
#存放pid文件的位置,每个实例会产生一个不同的pid文件,用来保存进程号。
pidfile /var/run/redis_6379.pid 
#端口号
port 6379                      
#持久化RDB的文件名
dbfilename dump6379.rdb

redis6380.conf

shell
include /myredis/redis.conf     
pidfile /var/run/redis_6380.pid  
port 6380                     
dbfilename dump6380.rdb

redis6381.conf

shell
include /myredis/redis.conf     
pidfile /var/run/redis_6381.pid  
port 6381                      
dbfilename dump6381.rdb

根据三台配置文件启动不同的redis

shell
redis-server /myredis/redis6379.conf
redis-server /myredis/redis6380.conf
redis-server /myredis/redis6381.conf
shell
ps -ef | grep redis

查看三台主机运行情况

连接三台终端

shell
redis-cli -p 6379
redis-cli -p 6380
redis-cli -p 6381

使用info replication 打印主从复制的相关信息

发现三台都是主机,并没有主从效果。

6381

6380

6379

配从(库)不配主(库)

shell
slaveof  <ip><port> #成为某个实例的从服务器

让6379为主,6380和6381为从 在6380和6381上执行:

shell
slaveof 127.0.0.1 6379 #具体主机ip写对应的ip 我这三台redis配一台本地服务器上的

测试读写分离

在主机上写数据

shell
set k11 kkk

在从机上读数据

测试成功

在从机上写数据

写入失败,测试成功