Springboot中的缓存使用

springboot 默认存储位置

默认缓存

复制代码
 JVM 堆内存, 默认缓存大小 16M,但旨在单个应用实例内有效,且缓存的数据量不会太大。

redis

复制代码
 缓存存储位置为 Redis, 分布式共享,多个应用实例可以共享缓存。

默认缓存使用步骤

1. 添加pom依赖

java 复制代码
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>

2.在主应用类或配置类上添加 @EnableCaching 注解

java 复制代码
	@SpringBootApplication
	@EnableCaching
	public class SpringBootApiApplication {
	
	    public static void main(String[] args) {
	        SpringApplication.run(SpringBootApiApplication.class, args);
	
	    }
	
	}

3.业务方法增加缓存注解 @Cacheable(value = "users", key = "#name"),即开启缓存服务。

java 复制代码
  	@RequestMapping(value = "/users")
	@Cacheable(value = "User", key = "#name")
	public List<User> getUsers(String  name) {
	
	    //创建用户集合
	    List<User> users = new ArrayList<>();
	
	    // 添加空值检查避免 NullPointerException
	    if (name != null && !name.isEmpty()) {
	        // 使用stream流过滤
	        users = users.stream()
	                .filter(user -> user.getName() != null && user.getName().contains(name))
	                .toList();
	    }
	
	    return users;
	 }

 PS: @Cacheable: 表示该方法的结果可以被缓存 value = "users": 指定缓存名称 key = "#name": 使用方法参数 name 作为缓存的键

4.修改删除业务方法需要清楚缓存使用注解 @CacheEvict(value = "users", key = "#name")

5.配置redis缓存

复制代码
 * 前提条件 项目已集成redis
 * Spring Boot 应用启动时扫描到 CacheConfig 类
 * 检测到 @Configuration 注解,将其注册为配置类
 * 检测到 @EnableCaching 注解,启用缓存基础设施
 * 初始化 CacheManager Bean 并配置 Redis 连接
java 复制代码
  @Configuration
  @EnableCaching
  public class CacheConfig {

       @Bean
       public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
           RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
               .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig())
              .build();
           return cacheManager;
       }
   }
   PS:
    *     //@Component 用于标注类,表示该类为Spring中的bean组件
    *     //@Bean 用于标注方法,表示这个方法返回的bean对象会被Spring管理,通常在配置类中使用,配合@Configuration注解
相关推荐
JustHappy6 小时前
古法编程秘籍(七):互联网到底是什么?把两台电脑怎么说话搞懂就够了
前端·后端·网络协议
Hommy886 小时前
【剪映小助手】添加图片接口(Add Images)
后端·github·剪映小助手·视频剪辑自动化
GetcharZp7 小时前
别再盲目用 OpenCV 读图了,这才是 CV 预处理的终极杀手锏!
后端
syt_biancheng9 小时前
Redis初识
数据库·redis·缓存
杨运交10 小时前
[032][缓存模块]基于Redis Bitmap的用户行为统计实战:签到与日活分析
数据库·redis·缓存
一 乐10 小时前
家政服务管理系统|基于springboot + vue家政服务管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·家政服务管理系统
IT_陈寒10 小时前
Vite热更新失效?可能你在用Windows
前端·人工智能·后端
椰椰椰耶11 小时前
[SpringCloud][14]OpenFeign参数传递方法
后端·spring·spring cloud
onething36512 小时前
Spring Boot + Spring AI 从入门到实战:7天转型计划 Day 3 —— 消息表设计 + 级联删除 + 事务管理
人工智能·后端
荣江12 小时前
Hermes Agent 代码仓库打包工具使用指南(repomix-rs 高性能版)
后端