SpringCache注解的基本使用

本文详细介绍了SpringCache的注解使用,包括@EnableCaching、@Cacheable、@CachePut和@CacheEvict。通过这些注解,可以在不修改业务代码的情况下实现缓存功能,提高应用性能。例如,@CachePut用于更新缓存,@CacheEvict用于清除缓存,而@Cacheable则在方法执行前检查缓存并决定是否执行方法。此外,还展示了如何结合SpEL表达式设置缓存键,并给出了集成Redis的配置示例。

SpringCache注解的基本使用

SpringCache介绍

使用注解对数据进行缓存功能的框架,只需要简单地加一个注解,就能实现缓存功能,大大简化我们在业务中操作缓存的代码。
注解说明
@EnableCaching开启缓存注解功能
@Cacheable在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
@CachePut将方法的返回值放到缓存中
@CacheEvict将一条或多条数据从缓存中删除

@CachePut注解

@CachePut (value=“xxx”,key = “#xxx”)说明:
位置: 方法的上方

​ 作用: 将方法返回值,放入缓存

​ value: 缓存的名称, 每个缓存名称下面可以有很多key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

key的写法如下: 

​ (1)#user.id : #user指的是方法形参的名称, id指的是user的id属性 , 也就是使用user的id属性作为key ;

​ (2)#result.id : #result代表方法返回值,该表达式 代表以返回对象的id属性作为key ;

/**
* CachePut:将方法返回值放入缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CachePut(value = "userCache", key = "#result.id")
@PostMapping
public User save(User user){
    userService.save(user);
    return user;
}

@CacheEvict注解

@CacheEvict 说明:

​ 作用: 清理指定缓存

​ value: 缓存的名称,每个缓存名称下面可以有多个key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

/**
* CacheEvict:清理指定缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CacheEvict(value = "userCache",key = "#p0")  //#p0 代表第一个参数
//@CacheEvict(value = "userCache",key = "#root.args[0]") //#root.args[0] 代表第一个参数
//@CacheEvict(value = "userCache",key = "#id") //#id 代表变量名为id的参数
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
    userService.removeById(id);
}

@Cacheable注解

@Cacheable 说明:

​ 作用: 在方法执行前,spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中

​ value: 缓存的名称,每个缓存名称下面可以有多个key

​ key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法

* Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@Cacheable(value = "userCache",key = "#id")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
    User user = userService.getById(id);
    return user;
}

@Cacheable 缓存非null值

在@Cacheable注解中,提供了两个属性分别为: condition, unless 。

condition : 表示满足什么条件, 再进行缓存 ;
unless : 表示满足条件则不缓存 ; 与上述的condition是反向的 (redis);

/**
 * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
 * value:缓存的名称,每个缓存名称下面可以有多个key
 * key:缓存的key
 * condition:条件,满足条件时才缓存数据
 * unless:满足条件则不缓存
 */
@Cacheable(value = "userCache",key = "#id", unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
    User user = userService.getById(id);
    return user;
}

@Cacheable key值包含参数对象的多个属性

在list方法中进行查询时,有两个查询条件,如果传递了id,根据id查询; 如果传递了name, 根据name查询,那么我们缓存的key在设计的时候,就需要既包含id,又包含name。 具体的代码实现如下:

@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
@GetMapping("/list")
public List<User> list(User user){
    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(user.getId() != null,User::getId,user.getId());
    queryWrapper.eq(user.getName() != null,User::getName,user.getName());
    List<User> list = userService.list(queryWrapper);
    return list;
}

集成Redis

(1) 导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

(2)application.yml配置

spring:
  redis:
    host: localhost
    port: 6379
    password: xxxx
    database: 0
### Spring Cache 注解详解:含义与使用方法 Spring Cache 是 Spring 框架中用于简化缓存管理的模块,通过注解的方式实现对缓存的声明式控制。开发者可以利用这些注解在不侵入业务逻辑的情况下实现缓存的读取、更新和删除操作。 #### `@Cacheable` 注解注解用于标记一个方法的结果需要被缓存。当方法被调用时,Spring 会先检查缓存中是否存在对应的数据,如果存在则直接返回缓存结果,否则执行方法并将结果放入缓存中。可以通过 `cacheNames` 或 `value` 属性指定缓存名称,通过 `key` 属性定义缓存键值。 示例: ```java @Cacheable(cacheNames = "users", key = "#id") public User getUserById(Long id) { return userRepository.findById(id); } ``` 上述代码表示每次调用 `getUserById` 方法时,Spring 会根据 `id` 构建缓存键,并尝试从名为 `users` 的缓存中获取数据[^2]。 #### `@CachePut` 注解注解用于更新缓存中的数据,无论缓存中是否存在旧数据,都会将方法的返回值写入缓存。通常用于更新操作,确保缓存中的数据始终是最新的。 示例: ```java @CachePut(cacheNames = "users", key = "#user.id") public User updateUser(User user) { return userRepository.save(user); } ``` 该方法在执行后会将更新后的用户对象存储到 `users` 缓存中,确保缓存与数据库同步[^5]。 #### `@CacheEvict` 注解注解用于清除缓存中的数据。可以用于删除单个条目或清空整个缓存区域。常用于删除操作之后,避免缓存中保留无效数据。 示例: ```java @CacheEvict(cacheNames = "users", key = "#id") public void deleteUserById(Long id) { userRepository.deleteById(id); } ``` 此方法会在删除用户后,从 `users` 缓存中移除对应的用户信息[^5]。 #### `@Caching` 注解注解允许在一个方法或类上同时指定多个缓存操作,包括 `cacheable`、`put` 和 `evict`。它适用于复杂的缓存需求,例如在同一方法上同时进行缓存读取、更新和删除操作。 示例: ```java @Caching( cacheable = @Cacheable("role"), evict = { @CacheEvict("role2"), @CacheEvict(value = "role", allEntries = true) }, put = { @CachePut(value = "role", key = "#role.id"), @CachePut(value = "role", key = "#role.name"), @CachePut(value = "role", key = "#role.account") } ) public Role find(Role role) { return null; } ``` 该方法展示了如何在一个方法上组合使用多种缓存操作,以满足更复杂的缓存逻辑需求[^5]。 #### 缓存命名空间与切面支持 除了基本注解功能外,Spring Cache 还支持通过自定义切面(Aspect)来增强缓存行为。例如,可以在切面类中定义前置通知(`@Before`)来实现更细粒度的缓存控制逻辑。 示例: ```java @Aspect @Component @CacheAspect public class CacheAspectForProductService { @Before("@cacheableMethod execution(* com.example.product.ProductService.get*(..))") public void cacheBeforeAdvice(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); String methodName = joinPoint.getSignature().getName(); String cacheKey = methodName + ":" + Arrays.toString(args); // 这里可以添加缓存检查和缓存填充逻辑 } } ``` 此切面类会在调用 `ProductService` 中所有以 `get` 开头的方法前执行缓存检查逻辑,进一步提升缓存的灵活性和可扩展性[^3]。 ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值