大致思路:
在多台数据服务器中,只有一台主服务器,而主服务器只负责写入数据,不负责
让外部程序读取数据。
主服务器在写入数据后,即刻将写入的数据命令发送给从服务器,从而使得主从
数据同步。
首先,我们将redis的配置文件redis.conf复制三份。
当前用户没有足够的权限的话,需要切换为root用户。
注:这里操作不是很规范,直接在redis的目录下复制的。最好新建文件夹,将这些配置文件统一放置。
这里配置的一主二从的模式。所以我们现在修改这三个配置文件。
将主服务器的配置文件中这几个配置改了:
daemonize yes 可以作为守护进程运行
logfile "6379.log" 日志文件
dbfilename dump6379.rdb RDB快照文件
将端口为6380从服务器的配置文件中几个配置改了:
port 6380 端口号
daemonize yes
pidfile /var/run/redis_6380.pid 线程文件
logfile "6380.log"
dbfilename dump6380.rdb
将端口为6381从服务器的配置文件中几个配置改了:
port 6381 端口号
daemonize yes
pidfile /var/run/redis_6381.pid 线程文件
logfile "6381.log"
dbfilename dump6381.rdb
然后我们指定配置文件的方式启动三个redis服务和客户端:
redis-server redis6379.conf
redis-cli -p 6379
redis-server redis6380.conf
redis-cli -p 6380
redis-server redis6381.conf
redis-cli -p 6381
这个时候我们可以通过info replication的命令查看具体信息。
我们可以看到当前的角色为maseter,连接从机数量为0.
然后我们在从机上执行命令 slaveof 主机IP 主机端口号
查看信息
我们可以在从机上看到已经连接到了主机(master_link_status:up),同时还有主机的IP,端口号等信息。
同时,在主机上也可以看到连接到的从机的相关信息:
这里我只开启了一个从机,所以connected_slaves的数值为1.
到这里我们的主从同步就配置完了。
过程中的几点问题:
- 如果redis主机配置了密码,从机在连接主机的过程中也需要密码。这里就需要去从机的配置文件中 更改masterauth的配置
masterauth 密码
不然在从机的日志中会一直发生下面的错误:
7317:S 28 May 14:54:36.103 * Connecting to MASTER 127.0.0.1:6379
7317:S 28 May 14:54:36.103 * MASTER <-> SLAVE sync started
7317:S 28 May 14:54:36.103 * Non blocking connect for SYNC fired the event.
7317:S 28 May 14:54:36.104 * Master replied to PING, replication can continue...
7317:S 28 May 14:54:36.104 * (Non critical) Master does not understand REPLCONF listening-port: -NOAUTH Authentication required.
7317:S 28 May 14:54:36.104 * (Non critical) Master does not understand REPLCONF capa: -NOAUTH Authentication required.
7317:S 28 May 14:54:36.104 * Partial resynchronization not possible (no cached master)
7317:S 28 May 14:54:36.105 # Unexpected reply to PSYNC from master: -NOAUTH Authentication required.
7317:S 28 May 14:54:36.105 * Retrying with SYNC...
7317:S 28 May 14:54:36.105 # MASTER aborted replication with an error: NOAUTH Authentication required.
2.(error) NOAUTH Authentication required.连接客户端口输入命令有这个错误,说明给redis设置了密码,这里我们就要用 auth 密码
命令进行验证 才可以正常使用。
3.关闭redis-server的命令要shutdown,不要直接CTRL+C什么的退出。其实在后台一直在跑着呢。