Redis搭建主从复用-(读写分离)(主备切换)(哨兵模式)
温馨提示: 如果你要是使用阿里云的Linux 服务器。先去阿里云安全组打开一些端口。否则在哨兵模式中会报错误
这也是我踩过的坑
先来说一下哨兵模式报的错误:
Next failover delay: I will not start a failover before
阿里云安全组
读写分离
直接看图就知道什么意思。主服务器具有读写,从服务器只有写
下面就是命令操作了
创建三个目录
mkdir -p /opt/redis/data
mkdir -p /opt/redis/log
mkdir -p /opt/redis/conf
复制到指定目录。然后修改文件名字,打开修改参数
cp redis.conf /opt/redis/conf
cd /opt/redis/conf
mv redis.conf redis-common.conf
vim redis-common.conf
由于实在太懒;所以修改后的参数后为:
touch redis-6379.conf
touch redis-6380.conf
touch redis-6381.conf
修改里面的每个conf
vim redis-6379.conf
配置文件
#引用公共配置
include /opt/redis/conf/redis-common.conf
#进程编号记录文件
pidfile /var/run/redis-6379.pid
#进程端口号
port 6379
#日志记录文件
logfile "/opt/redis/log/redis-6379.log"
#数据记录文件
dbfilename dump-6379.rdb
#追加文件名称
appendfilename "appendonly-6379.aof"
#下面的配置无需在 6379 里配置
#备份服务器从属于 6379 推荐配置配局域网 IP
#slaveof 120.76.134.149 6379
120.76.134.149为你的服务器地址
后面那两个也是如此配置,修改一下端口号,还有后面两个 这句话是:slaveof 120.76.134.149 6379 。不要注释掉,因为后面两个设置从服务器。
在你的./redis-server 的目录下,运行
./redis-server /opt/redis/conf/redis-6379.conf
./redis-server /opt/redis/conf/redis-6380.conf
./redis-server /opt/redis/conf/redis-6380.conf
复制三个会话出来
分别
./redis-cli -p 6379 -a root
./redis-cli -p 6380 -a root
./redis-cli -p 6381 -a root
做到这步,其实你已经成功。验证
6379端口下
set name wuhualiang
get name
6380端口下
set name shuaige //会报错,因为它只有读取没有存
主备切换 (使用哨兵模式)
前面操作和上面基本差不多,我直接上命令了
cd redis-6.0.6
cp sentinel.conf /opt/redis/conf
cd /opt/redis/conf
mv sentinel.conf sentinel-common.conf
vim sentinel-common.conf
参数修改后的
那个主机依然是你服务器地址
touch sentinel-26379.conf
touch sentinel-26380.conf
touch sentinel-26381.conf
修改配置
#引用公共配置
include /opt/redis/conf/sentinel-common.conf
#进程端口号
port 26379
#进程编号记录文件
pidfile "/var/run/sentinel-26379.pid"
#日志记录文件(为了方便查看日志,先注释掉,搭好环境后再打开)
logfile "/opt/redis/log/sentinel-26379.log"
在redis-sentinel 目录下启动
./redis-sentinel /opt/redis/conf/sentinel-26379.conf
./redis-sentinel /opt/redis/conf/sentinel-26380.conf
./redis-sentinel /opt/redis/conf/sentinel-26381.conf
ps -ef |grep sentinel
再开三个会话看日志
tail -f /opt/redis/log/sentinel-26379.log
测试主备切换
杀掉直接redis-6379.conf进程
kill -9 进程号
。成功后
等30秒
日志可以看出主从关系发生了变化