https://blog.51cto.com/u_16213693/10040764
SpringBoot 缓存之 @Cacheable 详细介绍-CSDN博客
@Cacheable
以下面代码为例:
PREFIX = "basis.";
@Cacheable(key = "#request.isIncludeCityInfo() + '' + #request.isIncludeAreaInfo()",
value = PREFIX + "facade.base.queryProvInfos",
condition = "#request != null")
public QueryResult<ProvInfo> queryProvInfos(ProvQueryRequest request) {
try {
doProcess();
} finally {
clearDb();
}
}
当@Cacheable这个注解修饰的方法时,缓存的存储过程如下:
- 检查条件:首先,Spring 会检查
condition
属性中的条件是否满足。如果request
对象为null
,则不会进行缓存。 - 生成键:如果条件满足,Spring 会根据
key
属性生成缓存的键。键是由request
对象的isIncludeCityInfo()
和isIncludeAreaInfo()
方法的返回值拼接而成的字符串。 - 检查缓存:Spring 会检查缓存中是否已经存在这个键对应的值。如果存在,则直接返回缓存中的值,而不执行方法。
- 执行方法并缓存结果:如果缓存中不存在这个键对应的值,Spring 会执行方法,并将方法的返回值存储到缓存中,键就是之前生成的键,缓存的名称是
value
属性定义的名称。
比如,请求构造的key为truefalse
,value/Cachename为basis.facade.base.queryProvInfos
。
key与value
key是缓存数据时使用的key,用来指定Spring缓存方法的返回结果时对应的key的。value用来指定缓存组件的名字,将方法的返回结果放在哪个缓存中,可以是数组的方式,支持指定多个缓存。也可以理解为:
- 缓存名称value定义了一个存储缓存条目的区域或空间。
- 键key是在这个区域或空间中用于查找特定缓存条目的标识符。
@CacheEvict
如果数据发生了改动,比如进行了update操作,则需要对缓存进行清除/刷新。
@CacheEvict(value = {PREFIX + "facade.base.queryProvInfos"},
allEntries = true)
public OperationResult update(ProvInfoVO request) {
return doProcess();
}
@CacheEvict
注解是 Spring 框架中用于清除缓存的一个注解。它的作用是在方法执行后,根据指定的条件清除缓存中的数据。
allEntries = true
表示清除该空间中的所有条目。
/**
* Whether all the entries inside the cache(s) are removed.
* <p>By default, only the value under the associated key is removed.
* <p>Note that setting this parameter to {@code true} and specifying a
* {@link #key} is not allowed.
*/
boolean allEntries() default false;
在这个例子中,选择清除的缓存空间为basis.facade.base.queryProvInfos
,但是并没有指定要清除的key,因此无论是否有allEntries = true
,都会清除该缓存区域中的所有条目。