Redis集群以及哨兵安装
基础信息
服务器节点:
xx.xx.xx.196(主节点 Master)
xx.xx.xx.197(从节点 Slave)
xx.xx.xx.198(从节点 Slave)
Redis密码:123456
哨兵主名称:mymaster
Redis端口:6379
哨兵端口:26379
一、所有机器统一执行
1. 安装依赖
apt update
apt install redis-server redis-sentinel -y2. 配置防火墙(永久生效)
vim /etc/iptables/rules.v4写入:
# Redis 数据端口
-A INPUT -p tcp --dport 6379 -j ACCEPT
# Redis 哨兵端口
-A INPUT -p tcp --dport 26379 -j ACCEPT生效:
iptables-restore < /etc/iptables/rules.v4二、Redis 配置(三台机器都配置)
vim /etc/redis/redis.conf统一配置
bind 0.0.0.0 # 允许所有IP访问
protected-mode no # 关闭保护模式
port 6379 # Redis 默认端口
requirepass 123456 # 访问密码
masterauth 123456 # 主从同步密码
daemonize yes # 后台运行
appendonly yes # 开启持久化,数据不丢重启并开机自启
systemctl restart redis-server
systemctl enable redis-server三、配置从节点(仅 197、198 执行)
vim /etc/redis/redis.conf
将这个添加到最后
replicaof xx.xx.xx.196 6379
systemctl restart redis-server四、验证主从(196 执行)
redis-cli -a '123456' info replication看到 connected_slaves:2 成功
五、哨兵配置(三台机器完全一样)
1. 关闭默认哨兵
systemctl stop redis-sentinel
systemctl disable redis-sentinel2. 创建哨兵配置
mkdir -p /etc/redis-sentinel
vim /etc/redis-sentinel/sentinel.conf哨兵配置
port 26379 # 哨兵端口
bind 0.0.0.0 # 允许外部访问
protected-mode no
daemonize yes # 后台运行
logfile /var/log/redis-sentinel.log
dir /tmp
# 监控主节点:mymaster = 主名称,2 = 2个哨兵同意即切换
sentinel monitor mymaster 100.64.255.196 6379 2
# 主节点密码
sentinel auth-pass mymaster one#screen$123
# 5秒没响应 = 宕机
sentinel down-after-milliseconds mymaster 5000
# 故障切换超时
sentinel failover-timeout mymaster 15000
sentinel parallel-syncs mymaster 13. 启动哨兵
redis-sentinel /etc/redis-sentinel/sentinel.conf4. 开机自启
编辑 rc.local
vim /etc/rc.local在 exit 0 上面加这一行
#!/bin/sh
# 开机启动 Redis 哨兵
/usr/bin/redis-sentinel /etc/redis-sentinel/sentinel.conf
exit 0给执行权限
chmod +x /etc/rc.local验证是否生效
ps -ef | grep sentinel5. 验证哨兵
redis-cli -p 26379 info sentinel成功显示:
status=ok,slaves=2,sentinels=3
六、程序调用哨兵模式
--- # redis 哨兵模式配置(替换原来的单机配置)
spring:
data:
redis:
# 哨兵模式配置
sentinel:
# 哨兵监听的主名称(固定为 mymaster)
master: mymaster
# 三个哨兵节点地址
nodes: xx.xx.xx.196:26379,xx.xx.xx.197:26379,xx.xx.xx.198:26379
# Redis 密码(和你环境一致)
password: 123456
# 数据库索引
database: 0
# 连接超时时间
timeout: 10s
# 是否开启ssl
ssl:
enabled: false
redisson:
enable: true
---
redisson:
# redis key前缀
keyPrefix:
# 线程池数量
threads: 4
# Netty线程池数量
nettyThreads: 8
# 哨兵模式配置(替换原来的 singleServerConfig)
sentinelServersConfig:
# 主节点名称(必须和哨兵一致)
masterName: mymaster
# 哨兵地址
sentinelAddresses: redis://xx.xx.xx.196:26379,redis://xx.xx.xx.197:26379,redis://xx.xx.xx.198:26379
# 主节点密码
password: 123456
# 最小空闲连接数
connectionMinimumIdleSize: 8
# 连接池大小
connectionPoolSize: 32
# 连接空闲超时,单位:毫秒
idleConnectionTimeout: 10000
# 命令等待超时,单位:毫秒
timeout: 3000
# 发布和订阅连接池大小
subscriptionConnectionPoolSize: 50七、常见检查命令
# 查看Redis主从状态
redis-cli -a '123456' info replication
# 查看哨兵集群状态
redis-cli -p 26379 info sentinel
# 查看Redis运行状态
systemctl status redis-server
# 查看哨兵进程
ps -ef | grep sentinel赞(1)
赏