简介
如果需要在Springcache中,为单个或一组redis缓存单独设置过期时间,可以在yml配置文件中如下编写:
spring:
cache:
cache-names: caches
redis:
# 全局缓存过期时间
time-to-live: 10m
# 自定义单个缓存name过期时间
time-to-live:
# 单个name过期时间
cache1: 10m
# 多个name过期时间,key包含特殊符号需要"[]"包裹
"[cache1,cache2]": 10m
那么,我们可以扩展@Cacheable注解,直接在注解属性上设置过期时间吗?
方案详情—修改源码
步骤
- 在@Cacheable注解中添加cacheTime属性
package org.springframework.cache.annotation;
@Target({
ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Reflective
public @interface Cacheable {
// ...
// @Modified
/**
* 过期时间
* @return
*/
String cacheTime() default "";
- CacheableOperation类中添加cacheTime属性
package org.springframework.cache.interceptor;
import org.springframework.lang.Nullable;
/**
* Class describing a cache 'cacheable' operation. * * @author Costin Leau
* @author Phillip Webb
* @author Marcin Kamionowski
* @since 3.1
*/public class CacheableOperation extends CacheOperation {
// ...其他属性...
// @Modified1
@Nullable
private final String cacheTime;
// @Modified2 修改构造
/**
* Create a new {@link CacheableOperation} instance from the given builder.
* @since 4.3
*/ public CacheableOperation(CacheableOperation.Builder b) {
super(b);
this.unless = b.unless;
this.sync = b.sync;
// @Modified
this.cacheTime = b.cacheTime;
}
// ...其他get方法...
// @Modified3
public String getCacheTime(){
return this.cacheTime;}
// @Modified4 修改Builder
/**
* A builder that can be used to create a {@link CacheableOperation}.
* @since 4.3
*/ public static class Builder extends CacheOperation.Builder {
// ...其他属性和setter...
// @Modified
private String cacheTime;
// @Modified