Redis主从复制

定义

  1. 一个redis服务可以由多个该服务的复制品,这个redis服务称为master,其他复制品称为slaves.
  2. master会一直将做空的数据更新同步给slaves.保持主从同步.
  3. 只要master可以执行写命令,slave只能执行读命令.

作用

分担了读的压力(高并发),由于写操作执行的相对较少.

实现方式

方式一,linux终端上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
redis-server --port 6300[从服务器端口号] --slaveof 127.0.0.1[主服务器IP地址] 6379[端口号] --masterauth[主服务器密码(如果有的话)]
# 从服务器
redis-server --port 6300 --slaveof 127.0.0.1 6379
# 客户端
[root@10-7-189-100 ~]# redis-cli -p 6300
127.0.0.1:6300> select 1
OK
# 从主服务器上复制过来的数据
127.0.0.1:6300[1]> keys *
1) "1"
# 只能读数据不能写入
127.0.0.1:6300[1]> set 1 2
(error) READONLY You can't write against a read only slave.
127.0.0.1:6300[1]> get 1
"2"

方式二(redis命令行)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 当然也可以在服务启动后在命令行执行slaveof IP PORT  绑定主服务
# 客户端
127.0.0.1:6300[1]> slaveof 127.0.0.1 6379
OK
# 主服务器
28696:M 08 Jan 16:53:10.291 * Synchronization with slave 127.0.0.1:6300 succeeded


# 当然也可以执行slaveof no one来解除主从
# 客户端
127.0.0.1:6300[1]> slaveof no one
OK
# 服务器端
28135:M 08 Jan 16:51:34.637 # Connection with slave 127.0.0.1:6300 lost.

方式三(配置文件启动)

1
2
3
4
5
# 只需要在配置文件中添加如下:
# 配置主服务器
slaveof 127.0.0.1 6379
# 配置端口
port 6300

补充:

配置文件添加后台启动,.

1
daemonize yes

问题:如果master 挂了怎么办?

1
2
3
4
5
6
一个master有多个slaves
slave挂一个,只是处理读的性能有所下降
master 如果挂了,那么所有写请求都无法执行.
怎么办?
我们只能在slaves中找一个把他当成master,然后修改别的slave重新指向新的master
# 以上是我们手动处理master挂了的方法,那么有没有什么自动实现的呢?这里我们就要讲一下sentinel哨兵.

redis-rentine哨兵

哨兵就是来帮我我们把手动需要干的事情,自动化.

安装哨兵

1
yum install redis-sentinel

新建哨兵配置文件

1
2
3
4
5
vim redis_sentin.conf
# 配置哨兵的端口
port 26379
# 配置哨兵监听服务器地址
sentinel monitor 6379[别名] 127.0.0.1[服务器地址] 6379[端口] 1[有几个哨兵服务认为主机挂了才切换]

启动哨兵

1
[root@10-7-189-100 ~]# redis-sentinel redis_sentinel.conf

可以自己去启几个redis服务模拟一下 master挂了之后 哨兵是如何切换master的.