Redis四种模式在Spring Boot框架下的配置

在Spring Boot框架下配置Redis的四种模式(单机模式、主从模式、哨兵模式、集群模式)可以通过以下方式实现:

  1. 单机模式

在application.properties或application.yml中配置Redis的连接信息:

application.properties

spring.redis.host=127.0.0.1

spring.redis.port=6379

spring.redis.password=yourpassword

或者

application.yml

spring:

redis:

host: 127.0.0.1

port: 6379

password: yourpassword

  1. 主从模式

Spring Boot默认不支持Redis主从模式的自动配置,需要手动配置LettuceConnectionFactory,在RedisTemplate中使用。

application.properties

spring.redis.master=master

spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.2:26379

spring.redis.password=yourpassword

使用RedissonClient配置主从模式:

@Bean

public RedissonClient redissonClient() {

Config config = new Config();

config.useMasterSlaveServers()

.setMasterAddress("redis://127.0.0.1:6379")

.addSlaveAddress("redis://127.0.0.2:6379", "redis://127.0.0.3:6379")

.setPassword("yourpassword");

return Redisson.create(config);

}

  1. 哨兵模式

在application.properties中配置哨兵模式:

application.properties

spring.redis.sentinel.master=mymaster

spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.2:26379

spring.redis.password=yourpassword

使用RedissonClient配置哨兵模式:

@Bean

public RedissonClient redissonClient() {

Config config = new Config();

config.useSentinelServers()

.addSentinelAddress("redis://127.0.0.1:26379", "redis://127.0.0.2:26379")

.setMasterName("mymaster")

.setPassword("yourpassword");

return Redisson.create(config);

}

  1. 集群模式

在application.properties中配置集群模式:

application.properties

spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.2:6379,127.0.0.3:6379

spring.redis.password=yourpassword

使用RedissonClient配置集群模式:

@Bean

public RedissonClient redissonClient() {

Config config = new Config();

config.useClusterServers()

.addNodeAddress("redis://127.0.0.1:6379", "redis://127.0.0.2:6379", "redis://127.0.0.3:6379")

.setPassword("yourpassword");

return Redisson.create(config);

}

以上配置涵盖了Redis的四种部署模式在Spring Boot框架下的配置方法。每种模式都有其特定的应用场景和配置要求,可以根据实际需求选择合适的模式进行配置。

相关推荐
洋洋技术笔记1 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward2 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
洋洋技术笔记2 天前
Spring Boot启动流程解析
spring boot·后端
怒放吧德德3 天前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
李慕婉学姐3 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
QQ5110082853 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe3 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
追风筝的人er3 天前
企业管理系统如何实现自定义首页与千人千面?RuoYi Office 给出了完整方案
vue.js·spring boot·spring cloud
Java水解3 天前
你真的会打印日志吗?基于 Spring Boot 的全方位日志指南
spring boot·后端