Redis环境搭建--主从模式

概念

通过持久化功能,Redis保证了即使在服务器重启的情况下也不会损失(或少量损失)数据,因为持久化会把内存中数据保存到硬盘上,重启会从硬盘上加载数据。
但是由于数据是存储在一台服务器上的,如果这台服务器出现硬盘故障等问题,也会导致数据丢失。为了避免单点故障,通常的做法是将数据库复制多个副本以部署在不同的服务器上,这样即使有一台服务器出现故障,其他服务器依然可以继续提供服务。为此, Redis 提供了复制(replication)功能,可以实现当一台数据库中的数据更新后,自动将更新的数据同步到其他数据库上。

在复制的概念中,数据库分为两类,一类是主数据库(master),另一类是从数据库(slave)。主数据库可以进行读写操作,当写操作导致数据变化时会自动将数据同步给从数据库。而从数据库一般是只读的,并接受主数据库同步过来的数据。一个主数据库可以拥有多个从数据库,而一个从数据库只能拥有一个主数据库。

主从数据库的配置

主数据库不用配置,从redis的conf文件中可以加载从数据库的信息,也可以在启动时,使用 redis-server --port 6380 --slaveof 127.0.0.1 6379
从数据库一般是只读,可以改为可写,但写入的数据很容易被主同步没,所以还是只读就可以。
也可以在运行时使用slaveof ip port命令,停止原来的主,切换成刚刚设置的主 slaveof no one会把自己变成主

一主两从环境搭建

  • 本地编译安装
mkdir -p /home/apps
cd /home/apps
wget http://download.redis.io/releases/redis-5.0.5.tar.gz
tar xzf redis-5.0.5.tar.gz
cd redis-5.0.5
make
  • 复制&修改配置文件
mkdir configs
cp redis.conf configs
cd configs

# 作为主
cp redis.conf redis7000.conf
# 作为从
cp redis.conf redis7001.conf
cp redis.conf redis7002.conf
  • 主节点配置
port 7000
daemonize  yes
requirepass 123456
pidfile /var/run/redis_7000.pid
logfile /var/log/redis/redis_7000.log
  • 从节点配置
port 7001
daemonize  yes
requirepass 123456
masterauth 123456
replicaof 127.0.0.1 7000
pidfile /var/run/redis_7001.pid
logfile /var/log/redis/redis_7001.log

port 7002
daemonize  yes
requirepass 123456
masterauth 123456
replicaof 127.0.0.1 7000
pidfile /var/run/redis_7002.pid
logfile /var/log/redis/redis_7002.log
  • 集群查看
../src/redis-cli -p 7000 -a 123456
127.0.0.1:7000> info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=7001,state=online,offset=224,lag=0
slave1:ip=127.0.0.1,port=7002,state=online,offset=224,lag=1
master_replid:1dde0f60b747564b1e469ddab6382a935cc1bce7
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:224
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:1
repl_backlog_histlen:224
  • 启动
../src/redis-server redis7000.conf
../src/redis-server redis7001.conf
../src/redis-server redis7002.conf

测试

  • 主从复制测试
# 主节点写入数据
../src/redis-cli -p 7000 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:7000> set aaa 111
OK
127.0.0.1:7000>

# 从节点获取数据
../src/redis-cli -p 7001 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:7001> get aaa
"111"
127.0.0.1:7001>

../src/redis-cli -p 7002 -a 123456
Warning: Using a password with '-a' or '-u' option on the command line interface may not be safe.
127.0.0.1:7002> get aaa
"111"
127.0.0.1:7002>

posted @ 2019-09-06 15:38  飞_2016  阅读(311)  评论(0编辑  收藏  举报