背景
redis的主从模式,也是可以起到读写分离以及实时备份的目的,但是当我们的主从出现故障时,程序端无法感知其故障节点并自动切换,需要手动更改,这就让我们特别难受。想想如果是深夜出现这个问题,那有多么痛苦,所以我们可以使用Redis的哨兵模式来达到我们想要的目的
我们配置Redis哨兵需要先配置主从,再来配置哨兵模式,架构如下:
redis-master:127.0.0.1:6379
redis-slave:127.0.0.1:6380
redis-slave:127.0.0.1:6381
redis-sentinel:127.0.0.1:16381, 127.0.0.1:26381, 127.0.0.1:36381
配置主从
主redis直接启动,不需要任何配置
redis-server /etc/6379.conf
在两个slave中, 分别修改如下配置,并启动:
# slaveof <masterip> <masterport>
slaveof 127.0.0.1 6381
看下如下配置,我们的主从便配置完成
[root@localhost etc]# redis-cli -p 6379 info Replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=6380,state=online,offset=6620,lag=1
slave1:ip=127.0.0.1,port=6381,state=online,offset=6620,lag=1
master_repl_offset:6753
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:2
repl_backlog_histlen:6752
role 表示当前的节点为主节点
slave 是另外两台从节点的地址
配置哨兵
哨兵的配置文件在redis的安装包中便有,我们复制出来便可以使用
cp /usr/local/redis/sentinel.conf /etc/sentinel-16379.conf
cp /usr/local/redis/sentinel.conf /etc/sentinel-26379.conf
cp /usr/local/redis/sentinel.conf /etc/sentinel-26379.conf
需要修改的配置如下:
# The port that this sentinel instance will run on
port 16379
#3个配置文件使用不同的端口
# Note: master name should not include special characters or spaces.
# The valid charset is A-z 0-9 and the three characters ".-_".
sentinel monitor mymaster 127.0.0.1 6379 2
#mymaster 是主节点的另名, 127.0.0.1 6379 表示需要监控这个主节点, 2 表示判断主节点失败至少需要2台sentinel节点同意
daemonize yes
#表示以后台的方式启动
执行如下命令启动sentinel:
[root@localhost etc]# redis-sentinel /etc/sentinel-16379.conf
[root@localhost etc]# redis-sentinel /etc/sentinel-26379.conf
[root@localhost etc]# redis-sentinel /etc/sentinel-36379.conf
然后
[root@localhost etc]# redis-cli -p 16379 info Sentinel
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
master0:name=mymaster,status=ok,address=127.0.0.1:6379,slaves=2,sentinels=3
看到sentinels则表示哨兵已经全部上线
Sentinel模式下,客户端的连接
我们现在使用的哨兵模式,当然不可以直接连接redis-server了,应该连接到Sentinel,返回连接地址才对。
以Python为例,先安装redis包,然后:
[root@localhost ~]# python
Python 2.6.6 (r266:84292, Nov 22 2013, 12:16:22)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from redis.sentinel import Sentinel #导入redis-sentinel方式
>>> sentinel = Sentinel([('127.0.0.1', 16379),('127.0.0.1', 26379),('127.0.0.1', 36379)], socket_timeout=0.1) #连接redis-sentinel
>>> sentinel.discover_master('mymaster') #返回master的地址
('127.0.0.1', 6381)
>>> sentinel.discover_slaves('mymaster') #返回slave的地址
[('127.0.0.1', 6380), ('127.0.0.1', 6379)]
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1) #在master中加入字段
>>> master.set('aa', 'bb')
True
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1) #从slave中读取
>>> slave.get('aa')
'bb'
完结
以上便是Redis-sentinel的搭建与使用方式了,如果有什么问题的话,欢迎大家一起讨论