Redis构建简单的主从复制
原理:
当设置好slave服务器后,slave会建立和master的连接,然后发送sync命令。无论是第一次同步建立的连接还是连接断开后的重新连
接,master都会启动一个后台进程,将数据库快照保存到文件中,同时master主进程会开始收集新的写命令并缓存起来。后台进程完成写文件
后,master就发送文件给slave,slave将文件保存到磁盘上,然后加载到内存恢复数据库快照到slave上。
配置前提,关闭防火墙或允许redis端口通行
Centos7
IP:10.0.0.128(master)
IP:10.0.0.129(slave)
主服务器配置:
下载安装包,解压并编译;
[[email protected] ~]# cd /usr/local/src/ [[email protected] src]# wget [[email protected] src]# tar -zxvf redis-stable.tar.gz [[email protected] src]# mv redis-stable /usr/local/redis [[email protected] src]# cd /usr/local/redis/ [[email protected] redis]# make && make install
copy配置文件redis.conf到/etc/目录下
[[email protected] redis]# cp redis.conf /etc/
修改配置文件;
[[email protected] ~]# vim /etc/redis.conf daemonize yes #开启redis进程 pidfile /var/run/redis_6379.pid #redis进程存放位置 dbfilename dump.rdb #指定快照文件名 dir /var/lib/redis #快照存储位置 masterauth 123456 #主库认证密码 requirepass 123456 #从库连接密码 #bind 127.0.0.1 #注释
启动redis服务;
[[email protected] redis]# /usr/local/bin/redis-server /etc/redis.conf [[email protected] redis]# ps -ef |grep redis root 5925 1 0 20:07 ? 00:00:00 /usr/local/bin/redis-server *:6379 root 5973 1614 0 20:09 pts/0 00:00:00 grep --color=auto redis
从服务器配置;
配置与主服务器一样,只需要修改配置文件,如下:
slaveof 10.0.0.128 6379 #指向主服务器 masterauth 123456 #主库设置的密码
启动服务;
[[email protected] ~]# /usr/local/bin/redis-server /etc/redis.conf
测试:
主服务器
127.0.0.1:6379> AUTH 123456 OK 127.0.0.1:6379> INFO replication # Replication role:master connected_slaves:1 slave0:ip=10.0.0.129,port=6379,state=online,offset=2571,lag=1 master_replid:c44ed3b15b076872c1091054cfd1f0fddd54c0e6 master_replid2:0000000000000000000000000000000000000000 master_repl_offset:2571 second_repl_offset:-1 repl_backlog_active:1 repl_backlog_size:1048576 repl_backlog_first_byte_offset:1 repl_backlog_histlen:2571 127.0.0.1:6379> 127.0.0.1:6379> set hello world OK 127.0.0.1:6379> get hello "world" 127.0.0.1:6379
从服务器
[[email protected] ~]# redis-cli 127.0.0.1:6379> 127.0.0.1:6379> AUTH 123456 OK 127.0.0.1:6379> INFO replication # Replication role:slave master_host:10.0.0.128 master_port:6379 master_link_status:up master_last_io_seconds_ago:9 master_sync_in_progress:0 slave_repl_offset:2718 slave_priority:100 slave_read_only:1 connected_slaves:0 master_replid:c44ed3b15b076872c1091054cfd1f0fddd54c0e6 master_replid2:0000000000000000000000000000000000000000 master_repl_offset:2718 second_repl_offset:-1 repl_backlog_active:1 repl_backlog_size:1048576 repl_backlog_first_byte_offset:1 repl_backlog_histlen:2718 127.0.0.1:6379> get hello "world" 127.0.0.1:6379> set test hello (error) READONLY You can‘t write against a read only slave. 127.0.0.1:6379> ####从服务器只读
###其它命令
删除keys:
127.0.0.1:6379>del keyname
当主服务器down,可以用一下命令将从升主:
127.0.0.1:6379> SLAVEOF NO ONE
时间: 2024-10-10 04:26:53