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)
主服务器配置:
下载安装包,解压并编译;
[root@master ~]# cd /usr/local/src/[root@master src]# wget
[root@master src]# tar -zxvf redis-stable.tar.gz
[root@master src]# mv redis-stable /usr/local/redis
[root@master src]# cd /usr/local/redis/
[root@master redis]# make && make install
copy配置文件redis.conf到/etc/目录下
[root@master redis]# cp redis.conf /etc/
修改配置文件;
[root@master ~]# 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服务;
[root@master redis]# /usr/local/bin/redis-server /etc/redis.conf[root@master redis]# ps -ef |grep redisroot 5925 1 0 20:07 ? 00:00:00 /usr/local/bin/redis-server *:6379root 5973 1614 0 20:09 pts/0 00:00:00 grep --color=auto redis
从服务器配置;
配置与主服务器一样,只需要修改配置文件,如下:
slaveof 10.0.0.128 6379 #指向主服务器masterauth 123456 #主库设置的密码
启动服务;
[root@slave ~]# /usr/local/bin/redis-server /etc/redis.conf
测试:
主服务器
127.0.0.1:6379> AUTH 123456OK127.0.0.1:6379> INFO replication# Replicationrole:masterconnected_slaves:1slave0:ip=10.0.0.129,port=6379,state=online,offset=2571,lag=1master_replid:c44ed3b15b076872c1091054cfd1f0fddd54c0e6master_replid2:0000000000000000000000000000000000000000master_repl_offset:2571second_repl_offset:-1repl_backlog_active:1repl_backlog_size:1048576repl_backlog_first_byte_offset:1repl_backlog_histlen:2571127.0.0.1:6379> 127.0.0.1:6379> set hello worldOK127.0.0.1:6379> get hello"world"127.0.0.1:6379
从服务器
[root@slave ~]# redis-cli 127.0.0.1:6379> 127.0.0.1:6379> AUTH 123456OK127.0.0.1:6379> INFO replication# Replicationrole:slavemaster_host:10.0.0.128master_port:6379master_link_status:upmaster_last_io_seconds_ago:9master_sync_in_progress:0slave_repl_offset:2718slave_priority:100slave_read_only:1connected_slaves:0master_replid:c44ed3b15b076872c1091054cfd1f0fddd54c0e6master_replid2:0000000000000000000000000000000000000000master_repl_offset:2718second_repl_offset:-1repl_backlog_active:1repl_backlog_size:1048576repl_backlog_first_byte_offset:1repl_backlog_histlen:2718127.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
本文出自 “XiaoBingZ” 博客,请务必保留此出处http://1767340368.blog.51cto.com/13407496/1981079