Spring Boot整合Spring Cache及Redis过程的示例分析
发表于:2025-11-07 作者:千家信息网编辑
千家信息网最后更新 2025年11月07日,这篇文章将为大家详细讲解有关Spring Boot整合Spring Cache及Redis过程的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1.安装red
千家信息网最后更新 2025年11月07日Spring Boot整合Spring Cache及Redis过程的示例分析
这篇文章将为大家详细讲解有关Spring Boot整合Spring Cache及Redis过程的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1.安装redis
a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址:
https://github.com/MicrosoftArchive/redis/releases
b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.windows.conf,启动redis(关闭cmd窗口即停止)
2.使用
a.创建SpringBoot工程,选择maven依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf ..... org.springframework.boot spring-boot-starter-data-redis
b.配置 application.yml 配置文件
server: port: 8080spring: # redis相关配置 redis: database: 0 host: localhost port: 6379 password: jedis: pool: # 连接池最大连接数(使用负值表示没有限制) max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-wait: -1ms # 连接池中的最大空闲连接 max-idle: 5 # 连接池中的最小空闲连接 min-idle: 0 # 连接超时时间(毫秒)默认是2000ms timeout: 2000ms # thymeleaf热更新 thymeleaf: cache: false
c.创建RedisConfig配置类
@Configuration@EnableCaching //开启缓存public class RedisConfig { /** * 缓存管理器 * @param redisConnectionFactory * @return */ @Bean public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { // 生成一个默认配置,通过config对象即可对缓存进行自定义配置 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); // 设置缓存的默认过期时间,也是使用Duration设置 config = config.entryTtl(Duration.ofMinutes(30)) // 设置 key为string序列化 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) // 设置value为json序列化 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer())) // 不缓存空值 .disableCachingNullValues(); // 对每个缓存空间应用不同的配置 Map configMap = new HashMap<>(); configMap.put("userCache", config.entryTtl(Duration.ofSeconds(60))); // 使用自定义的缓存配置初始化一个cacheManager RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) //默认配置 .cacheDefaults(config) // 特殊配置(一定要先调用该方法设置初始化的缓存名,再初始化相关的配置) .initialCacheNames(configMap.keySet()) .withInitialCacheConfigurations(configMap) .build(); return cacheManager; } /** * Redis模板类redisTemplate * @param factory * @return */ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(factory); // key采用String的序列化方式 template.setKeySerializer(new StringRedisSerializer()); // hash的key也采用String的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer()); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer()); return template; } /** * json序列化 * @return */ private RedisSerializer d.创建entity实体类
public class User implements Serializable { private int id; private String userName; private String userPwd; public User(){} public User(int id, String userName, String userPwd) { this.id = id; this.userName = userName; this.userPwd = userPwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; }}e.创建Service
@Servicepublic class UserService { //查询:先查缓存是是否有,有则直接取缓存中数据,没有则运行方法中的代码并缓存 @Cacheable(value = "userCache", key = "'user:' + #userId") public User getUser(int userId) { System.out.println("执行此方法,说明没有缓存"); return new User(userId, "用户名(get)_" + userId, "密码_" + userId); } //添加:运行方法中的代码并缓存 @CachePut(value = "userCache", key = "'user:' + #user.id") public User addUser(User user){ int userId = user.getId(); System.out.println("添加缓存"); return new User(userId, "用户名(add)_" + userId, "密码_" + userId); } //删除:删除缓存 @CacheEvict(value = "userCache", key = "'user:' + #userId") public boolean deleteUser(int userId){ System.out.println("删除缓存"); return true; } @Cacheable(value = "common", key = "'common:user:' + #userId") public User getCommonUser(int userId) { System.out.println("执行此方法,说明没有缓存(测试公共配置是否生效)"); return new User(userId, "用户名(common)_" + userId, "密码_" + userId); }}f.创建Controller
@RestController@RequestMapping("/user")public class UserController { @Resource private UserService userService; @RequestMapping("/getUser") public User getUser(int userId) { return userService.getUser(userId); } @RequestMapping("/addUser") public User addUser(User user){ return userService.addUser(user); } @RequestMapping("/deleteUser") public boolean deleteUser(int userId){ return userService.deleteUser(userId); } @RequestMapping("/getCommonUser") public User getCommonUser(int userId) { return userService.getCommonUser(userId); }}@Controllerpublic class HomeController { //默认页面 @RequestMapping("/") public String login() { return "test"; }}g.在 templates 目录下,写书 test.html 页面
test 测试
关于"Spring Boot整合Spring Cache及Redis过程的示例分析"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
缓存
配置
序列
用户
方式
系统
错误
最大
密码
方法
时间
用户名
篇文章
示例
过程
分析
整合
代码
对象
更多
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
广东企业存储服务器
东莞微信软件开发订制
网络安全管理局的职能
网游的血量是存在服务器么
javaweb连接数据库密码
龙源主流数据库吗
孤岛惊魂6服务器无法连接 ps
济南计算机软件开发机构
濮阳大树网络技术有限公司
越权删除数据库被判多久
网络安全思维导图高清
江苏提供网络技术服务电话
四川网络安全资讯
区块链属于网络技术吗
网络安全涉及国防
甘肃省斯玛特服务器云空间
山东技术管理软件开发平台
软件开发公司的软件服务费
宽带专线需要加服务器吗
铭万互联网科技有限公司
为什么浙江省三级数据库很少
日本数据库设计图
北京冬奥网络安全保障中心在奇安信正式启动
dhcp服务器搭建内网oa
中级职称软件开发类
存储服务器维修上门收费
千锋网络安全百度云盘
intel 金牌服务器
嵌入式软件开发哪家可靠
潮州数字软件开发销售厂