Redis在windows和Alibaba Cloud linux下如何配置主从和哨兵
window环境
主从配置和启动
- 复制redis文件夹
- 修改从库的配置文件“redis.windows.conf”,并添加“slaveof”属性
#端口号
port 6380
#是否为守护进程
daemonize no
#从库是否为只读
slave-read-only yes
#是谁的从库
slaveof {masterHost} {masterPort}
- 使用 redis-server.exe redis.windows.conf 启动
哨兵配置和启动
- 在redis主库和从库的文件夹中分别创建一个新的配置文件“sentinel.conf”
- 在配置文件“sentinel.conf”中添加配置
#端口号
port 26379
#sentinel monitor 主库名称 主库地址:主库端口号 客观下线数
sentinel monitor mymaster 127.0.0.1 6379 2
#是否为守护进程
daemonize yes
#日志文件地址
logfile “./sentinel_log.log”
- 使用“redis-server.exe sentinel.conf --sentinel”命令启动
注:每个redis-server可以同时启动库和哨兵,哨兵启动后无日志打印,并不是进程卡主。
配置文件中的主库地址,只是一个默认的主库(即redis启动时的主库地址)。在后续的运行中,无论哪个从库变成主库,都会继续被哨兵监听。
例如,默认情况下主库为6379,从库为6380和6381。
当主库下线后6380升为主库,6381改为6380的从库。当6379重新上线后,会变为6380的从库;
6381作为主库下线后,哨兵还是会监听到,继续在从库中推选一个变为主库,继续上述的行动。
Alibaba Cloud Linux中使用systemctl管理哨兵
我是使用"yum"来安装的redis。windows和linux配置方式基本一致,这里主要讲的是如何配置来使用“systemctl”来更方便的控制redis
yum install redis
主从配置和启动
推荐使用“find”命令来找redis相关的文件,会方便很多
- 找到“redis.conf”文件后,使用“cp”命令来复制从库配置
cp redis.conf redis_6380.conf
- 然后使用“vim”编辑文件
vim redis_6380.conf
- 修改配置文件
#端口号
port 6381
#日志文件
logfile “/var/log/redis/redis_6381.log”
#数据库文件名称
dbfilename “dump_6381.rdb”
#数据库地址
dir “/var/lib/redis_6381”
- 修改后到对应的路径创建缺少的文件(如:redis_6381.log、dump_6381.rdb)
- systemctl真正使用的文件是“/usr/lib/systemd/system/redis.service”
- 使用vim编辑该文件
- 使用“systemctl daemon-reload”来更新配置
- 然后使用“systemctl start 你配置的启动名称”来启动redis
- “systemctl status 启动名称”来查看启动情况
哨兵配置和启动
- 在redis配置文件的路径下,新建哨兵配置文件(当目标文件不存在时,vim会新建
vim redis_26379.conf
- 添加配置
port 26379
daemonize yes
logfile “/var/log/redis/sentinel/redis_26379.log”
sentinel monitor mymaster 127.0.0.1 6379 2
- 在“redis.service”目录下,复制“redis.service”文件
cp redis.service redis_26379.service
- 修改service文件,主要修改启动程序、配置文件、启动时服务名称
- 使用“systemctl start 启动名称”来启动服务
- 到你配置的日志文件地址查看日志
springboot整合redisTeamplate主从+哨兵
- 添加引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 添加配置
spring:
redis:
#哨兵配置
sentinel:
#默认情况下的主库名称
master: mymaster
nodes:
- 127.0.0.1:26379
- 127.0.0.1:26380
- 127.0.0.1:26381
- 直接在需要的地方引用实例即可
@Autowired
private StringRedisTemplate redis;
@GetMapping("redis")
public String redis(){
// redis.opsForValue().set("name123","test_2021");
return redis.opsForValue().get("name123");
}
注:主从配置中没有体现,但是sentinel会包含主从关系,在项目运行时依旧会有主从关系