Spring Cache 是基于 AOP(面向切面编程)实现的缓存框架,它提供了一套注解驱动的缓存管理机制。它不直接实现缓存,而是提供了一个抽象层,底层可以切换不同实现。
1 导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.7.3</version>
</dependency>
导入redis,spring Cache会自动使用redis。
2、核心注解
注解 | 说明 |
---|---|
@EnableCaching | 开启缓存注解功能,通常加在启动类上 |
@Cacheable | 在方法执行前先查询缓存中是否有数据,如果有数据,则直接返回缓存数据;如果没有缓存数据,调用方法并将方法返回值放到缓存中 |
@CachePut | 将方法的返回值放到缓存中 |
@CacheEvict | 将一条或多条数据从缓存中删除 |
@Cacheable
- 使用方法:标注在需要缓存结果的方法上,示例如下:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@Cacheable(value = "yourCacheName", key = "#param")
public String yourMethod(String param) {
// 方法逻辑,例如查询数据库等操作
return "result";
}
}
上述代码中,yourMethod
方法的结果会根据指定的缓存名称yourCacheName
和缓存键#param
(这里表示方法的param
参数)进行缓存。即 Key=value
/cacheNames
+ :: + key,下同。
- 标签属性:
value
/cacheNames
:指定缓存的名称,可以是一个或多个,如{"cache1", "cache2"}
。key
:指定缓存的键,支持 Spring 表达式语言(SpEL),可以通过方法参数等生成键。condition
:指定缓存的条件,只有满足条件时才会缓存,例如condition = "#param.length() > 0"
。unless
:指定不缓存的条件,例如unless = "#result == null"
。
@CachePut
- 使用方法:标注在方法上,保证方法执行后将返回值存入缓存,示例:
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@CachePut(value = "yourCacheName", key = "#entity.id")
public YourEntity updateYourEntity(YourEntity entity) {
// 更新数据库等操作
return updatedEntity;
}
}
这里updateYourEntity
方法执行后,返回的YourEntity
对象会根据yourCacheName
和#entity.id
作为键存入缓存。Key=value
/cacheNames
+ :: + key
- 标签属性:与 @Cacheable 类似,有
value
/cacheNames
、key
、condition
等属性,含义和用法一致。
@CacheEvict
- 使用方法:标注在方法上,用于从缓存中移除数据,示例:
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
@Service
public class YourService {
@CacheEvict(value = "yourCacheName", key = "#id")
public void deleteYourEntity(String id) {
// 删除数据库中对应数据的操作
}
}
当deleteYourEntity
方法被调用时,会根据yourCacheName
和#id
从缓存中移除对应的数据。
- 标签属性:
value
/cacheNames
:指定要清除的缓存名称。key
:指定要清除的缓存键。allEntries
:布尔类型,若为true
,则清除指定缓存中的所有数据。beforeInvocation
:布尔类型,若为true
,在方法执 行前就清除缓存;若为false
(默认),在方法成功执行后清除缓存。