Loading... ## 简介 <div class="tip inlineBlock share"> Spring Cache 是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能。 Spring Cache 提供了一层抽象,底层可以切换不同的cache实现。 具体就是通过 CacheManager 接口来统一不同的缓存技术。 CacheManager 是 Spring 提供的各种缓存技术抽象接口,这是默认的缓存技术,是缓存在Map中的,这也说明当服务挂掉的时候,缓存的数据就没了。 针对不同的缓存技术需要实现不同的 CacheManager | CacheManager | 描述 | | --------------------- | ---------------------------------------- | | EhCacheCacheManager | 使用 EhCache 作为缓存技术 | | GuavaCacheManager | 使用 Google 的 GuavaCache 作为缓存技术 | | RedisCacheManager | 使用 Redis 作为缓存技术 | </div> ## 基本配置: ### 导入坐标: ```java <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> ``` ### 开启注解功能 java在启动类 上加入 **@EnableCaching** 注解,开启缓存注解功能 ```java @Slf4j @SpringBootApplication @ServletComponentScan @EnableCaching public class ReggieApplication { public static void main(String[] args) { SpringApplication.run(ReggieApplication.class, args); log.info("springBoot项目启动成功……"); } } ``` ### 实体类实现序列化接口@Serializable ```java @Data public class Book implements Serializable { private Integer id; private String type; private String name; private String description; } ``` ## 常用注解: | 注解 | 说明 | | ---------------- | ------------------------------------------------------------------------------------------------------------------------- | | @EnableCaching | 开启缓存注解功能 | | @Cacheable | 在方法执行前 spring 先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中 | | @CachePut | 将方法的返回值放到缓存中 | | @CacheEvict | 将一条或多条数据从缓存中删除 | ### @Cacheable `@Cacheable`注解主要是在方法执行前 先查看缓存中是否有数据。如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中。 注解中的参数传递主要使用的是 **SpEL(Spring Expression Language)** 对数据进行获取传递,这有点类似于JSP中的EL表达式,常用方式如下几种: * “#p0”:获取参数列表中的第一个参数。其中的“#p”为固定写法,0为下标,代表第一个; * “#root.args[0]”:获取方法中的第一个参数。其中0为下标,代表第一个。 * “#user.id”:获取参数 user 的 id 属性。注意的是这里的 user 必须要和参数列表中的参数名一致 * “#result.id”:获取返回值中的 id 属性。 来自Spring Cache源码:Spring Expression Language (SpEL) expression used for making the method 在`@Cacheable`注解中有几种常用的属性可进行需求性设置: * value:缓存的名称,每个缓存名称下面可以有多个 key * key:缓存的key。 * condition:条件判断,满足条件时对数据进行缓存,值得注意的是该参数在Redis中无效 * unless:条件判断,满足条件时则不对数据进行缓存,Redis中可使用该参数替代condition ```java @Cacheable(value = "userCache", key = "#id", unless = "#result == null") @GetMapping("/{id}") public User getById(@PathVariable Long id) { User user = userService.getById(id); return user; } ``` ### @CachePut `@CachPut`注解主要是将方法的返回值放到缓存中。这里同样是使用SpEL获取数据,常用的属性如下: * value:缓存的名称,每个缓存名称下面可以有多个 key * key:缓存的key。 * condition:条件判断,满足条件时对数据进行缓存,值得注意的是该参数在Redis中无效 * unless:条件判断,满足条件时则不对数据进行缓存,Redis中可使用该参数替代condition ```java @CachePut(value = "userCache", key = "#user.id") @PostMapping public User save(User user) { userService.save(user); return user; } ``` ### @CacheEvict #### 删除单个数据 `@CacheeEvict`主要是将一条或多条数据从缓存中删除,同样使用SpEL获取数据,常用的属性如下: * value:缓存的名称,每个缓存名称下面可以有多个 key * key:缓存的key。 * condition:条件判断,满足条件时对数据进行缓存,值得注意的是该参数在Redis中无效 * unless:条件判断,满足条件时则不对数据进行缓存,Redis中可使用该参数替代condition ```java @CacheEvict(value = "userCache", key = "#result.id") @PutMapping public User update(User user) { userService.updateById(user); return user; } ``` #### 删除全部数据 这里用到了一个新属性allEntries,其是boolean类型,表示是否需要清除缓存中的所有元素。默认为false,表示不需要。当指定了 allEntries 为 true 时,Spring Cache将忽略指定的 key。有的时候我们需要 Cache 一下清除所有的元素,这比一个一个清除元素更有效率。 ```java @CacheEvict(value = "setmealCache",allEntries = true) @PutMapping public Result<String> updateWithDish(@RequestBody SetmealDto setmealDto) { log.info(setmealDto.toString()); setmealService.updateWithDish(setmealDto); return Result.success("套餐修改成功"); } ``` ## 使用Redis当作缓存产品 ### 导入坐标: ```java <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` ### yml配置 ```java spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC username: root password: 123456789 #--redis-- cache: type: redis redis: key-prefix: sms_ cache-null-values: false time-to-live: 10s redis: host: localhost port: 6379 ``` ### 使用: springcache会把缓存的数据自动放入redis中,不需要我们操作。 最后修改:2022 年 08 月 15 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果文章有用,请随意打赏。