欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

redis 备份以及主从复制  

程序员文章站 2022-03-20 20:59:34
...

 

1.redis备份

有两种方式:rdb和aof

     rdb:全量备份     时效性较差  数据丢失可能性大   恢复快  压缩率高(文件小)

     aof:增量备份      时效性高     数据 丢失可能性小 恢复慢   未压缩(文件大,BGREWRITEAOF可能稍微            减小一点体积) 

 官方建议两种方式都开启。

     默认rdb是开启的

     aof默认关闭,需要打开的话,编辑redis.conf大概593行左右,把appendonly no改为appendonly yes

 

 

2.主从复制

 三台服务器规划:

192.168.1.2 --master    6379

192.168.1.3 --slavesl1  6379

192.168.1.4 --slavesl2  6379

mater不用配置,

打开slave1的redis.conf 大概256行左右   # slaveof <masterip> <masterport>  把注释去掉  

修改为:slaveof 192.168.1.2 6379

slave2和slave1一样修改redis.conf配置文件。

然后启动三台服务器,查看:

使用redis-cli连接master  输入命令 info replication

# Replication

role:master

connected_slaves:2

slave0:ip=192.168.1.3,port=6379,state=online,offset=3333,lag=1

slave1:ip=192.168.1.4,port=6379,state=online,offset=3333,lag=0

master_repl_offset:3333

repl_backlog_active:1

repl_backlog_size:1048576

repl_backlog_first_byte_offset:2

repl_backlog_histlen:3332

 

使用redis-cli连接slave 输入命令 info replication

role:slave

master_host:192.168.1.2

master_port:6379

master_link_status:up

master_last_io_seconds_ago:0

master_sync_in_progress:0

slave_repl_offset:3319

slave_priority:100

slave_read_only:1

connected_slaves:0

master_repl_offset:0

repl_backlog_active:0

repl_backlog_size:1048576

repl_backlog_first_byte_offset:0

repl_backlog_histlen:0

就这么简单,主从复制就完成了。

 

下面说说主从复制的工作方式:

参考redis官方:http://redis.io/topics/replication

How Redis replication works

If you set up a slave, upon connection it sends a PSYNC command.

If this is a reconnection and the master has enough backlog, only the difference (what the slave missed) is sent. Otherwise what is called a full resynchronization is triggered.

When a full resynchronization is triggered, the master starts a background saving process in order to produce an RDB file. At the same time it starts to buffer all new write commands received from the clients. When the background saving is complete, the master transfers the database file to the slave, which saves it on disk, and then loads it into memory. The master will then send all buffered commands to the slave. This is done as a stream of commands and is in the same format of the Redis protocol itself.

You can try it yourself via telnet. Connect to the Redis port while the server is doing some work and issue the SYNCcommand. You'll see a bulk transfer and then every command received by the master will be re-issued in the telnet session.

Slaves are able to automatically reconnect when the master-slave link goes down for some reason. If the master receives multiple concurrent slave synchronization requests, it performs a single background save in order to serve all of them.

 

主要就是说:redis master会启动一个后台进程把内存数据写入到rdb文件中,写rdb文件这段时间的所有新命令会被缓存起来,不会执行,当rdb写好以后,同步到slave节点,同步完成以后,再把所有缓存的命令发送到slave去执行。