redis主从,哨兵一条龙
Redis
Redis 是一种开源(BSD 许可)、内存中数据结构存储,用作数据库、缓存和消息代理。Redis 提供了诸如字符串、散列、列表、集合、带范围查询的排序集合、位图、超级日志、地理空间索引和流等数据结构。Redis 内置复制、Lua 脚本、LRU 驱逐、事务和不同级别的磁盘持久化,并通过 Redis Sentinel 和 Redis Cluster 自动分区提供高可用性
一.redis概述
Reids优点:
- Redis作为nosql数据库功能强大易扩展
- 灵活数据模型
- 大数据量,高性能
- 高可用
Redis的应用场景:
- 缓存
- 网站访问统计
- 任务队列
- 数据过期处理
- 应用排行榜
- 分布式集群架构中的session分离
二. redis安装
准备环境:http://download.redis.io/releases/
redis-5.0.7.tar.gz
应用主机:192.168.200.{113/114/115}
应用模块:redis主从
Redis哨兵(监控高可用)
主机版本:CentOS Linux release 7.1.1503 (Core)
Linux BJ-JXQ-VM-26-21 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
解压缩安装redis
tar xf redis-5.0.7.tar.gz -C /usr/local/
cd /usr/local/redis-5.0.7/
make && make install
主从模式
修改主节点配置文件
vim redis.conf
bind 0.0.0.0
protected-mode no
daemonize yes
logfile "/usr/local/redis-5.0.7/redis.log"
修改从节点配置文件
vim redis.conf
bind 0.0.0.0
protected-mode no
daemonize yes
logfile "/usr/local/redis-5.0.7/redis.log"
replicaof 192.168.200.115 6379
启动redis
./redis-server /usr/local/redis-5.0.7/redis.conf
过滤查看redis是否启动
ps -ef | grep -v grep | grep redis
查看主从状态
主从测试
主节点:
127.0.0.1:6379> set a 1
OK
127.0.0.1:6379> get a
"1"
从节点:
127.0.0.1:6379> get a
"1"
127.0.0.1:6379>
三. 哨兵模式
Redis的主从复制下,一旦主节点由于故障不能提供服务,需要人工将从节点晋升为主节点,同时还要通知应用方更新主节点地址,对于很多应用场景这种故障处理的方法是无法接受的。但是Redis从2.8开始正式提供了Redis Sentinel(哨兵)架构来解决这个问题。
Redis Sentinel是一个分布式架构,其中包含若干个Sentinel节点和Redis数据节点,每个Sentinel节点会对数据节点和其余Sentinel节点进行监控,当它发现节点不可达时,会对节点做下线标识。如果被标识的是主节点,它还会和其他Sentinel节点进行“协商”,当大多数Sentinel节点都认为主节点不可达时,它们会选举出一个Sentinel节点来完成自动故障转移
修改哨兵配置文件
vim sentinel.conf
3台主机配置文件一样
daemonize yes
logfile "/usr/local/redis-5.0.7/sentinel.log"
sentinel monitor mymaster 192.168.200.115 6379 2
sentinel down-after-milliseconds mymaster 30000
sentinel failover-timeout mymaster 180000
启动哨兵模式
./redis-sentinel /usr/local/redis-5.0.7/sentinel.conf
查看是否启动
ps -ef | grep -v grep | grep sentinel
测试哨兵模式
在115上直接杀死redis
ps -ef | grep -v grep | grep redis
root 5489 1 0 14:32 ? 00:00:03 ./redis-server 0.0.0.0:6379
root 5528 1 0 14:51 ? 00:00:01 ./redis-sentinel *:26379 [sentinel]
kill 5489
转移成功114变成了master
注意事项
Redis的哨兵模式必须建立在主从之上,
尽量后台运行哨兵,
哨兵集群要大于半数最少3台
配置文件
vim sentinel.conf
logfile "/usr/local/redis-5.0.7/sentinel.log" 日志文件
sentinel monitor mymaster 192.168.200.115 6379 2 指定主哨兵节点
sentinel down-after-milliseconds mymaster 30000 防止脑裂的预连时间
sentinel failover-timeout mymaster 180000 选举时间