SpringCache注解实现⾃定义失效时间(升级版)SpringCache注解实现⾃定义失效时间
SpringCache Redis提供了开箱即⽤的缓存功能,但是美中不⾜的是官⽅只⽀持全部失效时间配置,在项⽬中我们可能需要对某⼀些接⼝针对性的配置失效时间,此时就需要⾃⼰来定制了。在此之前的项⽬中我实现过两种⽅式来解决该问题,但是粒度只能到类级别,同时配置也有⼀些不太合理的地⽅,这次做了优化,并且在公司的⽣产环境稳定运⾏了半年有余暂时还没发现问题,本着开源共享的精神,分享出来,本⼈代码能⼒有限,如果问题还望各位看官⼤佬多多包涵。
原理
通过获取⽅法前的注解值,⽐如:@CacheExpire(ttl = 10, unit = TimeUnit.SECONDS)得到配置的失效时间,因为我是通过⼀个map来存放某个⽅法以及对应的失效时间,map的泛型是Map<String, Duration>其中key是当前⽅法对应的缓存key,为了保证该key全局唯⼀,⽤spring cache⾃⼰的⽅式不太可⾏,所以在项⽬启动之前动态修改注解的值,动态添加keyGenerator为⾃定义的key⽣成器作为key。
举个例⼦:
启动前FooService.java
@CacheExpire(ttl = 1, unit = TimeUnit.MINUTES)
@Service
public class FooService {
@CacheExpire(ttl = 10, unit = TimeUnit.SECONDS)
@Cacheable
public Map<String,String> foo() {
Map<String,String> map = new HashMap<String, String>();
map.put("k1", "v1");
return map;
}
}
启动后经过⾃定义的代码处理会变成:
@CacheExpire(ttl = 1, unit = TimeUnit.MINUTES)
@Service
public class FooService {
// myKeyGenerator 是⾃定义的key⽣成器
// cacheNames 就是动态添加的值,规则是全类名.⽅法明
@CacheExpire(ttl = 10, unit = TimeUnit.SECONDS)
@Cacheable(keyGenerator="myKeyGenerator", cacheNames="com.bart.service.FooService.foo")
public Map<String,String> foo() {
Map<String,String> map = new HashMap<String, String>();
map.put("k1", "v1");
return map;
}
}
最终Map<String, Duration>⾥⾯存放的就是
{
"com.bart.service.FooService.foo" = PTS10
}
在spring cache 往 redis 中put值的时候调⽤我重写的逻辑,拿到当前⽅法的cacheNames从Map<String, Duration>取对应的失效时间从⽽实现了⽅法级别的粒度控制。
步骤
依赖
<project xmlns="/POM/4.0.0"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bart.springboot</groupId>
<artifactId>springboot-cache</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- 配置编译版本和编码格式 -->
<properties>
&ding>UTF-8</ding>
<mavenpiler.target>1.8</mavenpiler.target>
<mavenpiler.source>1.8</mavenpiler.source>
<commons-pool.version>1.6</commons-pool.version>
<skipTests>true</skipTests>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring boot 的缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 引⼊Redis得启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
<!--
再Spring2.X版本中使⽤Redis需要引⼊该依赖
1.X版本则不需要
-->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>${commons-pool.version}</version>
</dependency>
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>cacheable
<artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置⽂件
server:
port: 8888
spring:
profiles: dev
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
timeout: 10000 #连接超时时间
lettuce:
pool:
#最⼤连接数
max-active: 8
#最⼤阻塞等待时间(负数表⽰没限制)
max-wait: 0
#最⼤空闲
max-idle: 8
#最⼩空闲
min-idle: 0
⾃定义类
注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import urrent.TimeUnit;
/**
* 缓存失效的注解
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheExpire {
/**
* 失效时间,默认是60
* @return
*/
public long ttl() default 60L;
/**
* 单位,默认是秒
* @return
*/
public TimeUnit unit() default TimeUnit.SECONDS;
}
⾃定义key⽣成器
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import flect.Method;
/
**
* Created by BartG on 2019/1/23.
* ⾃定义的缓存key⽣成器
*/
@Component("myCacheKeyGenerator")
public class MyCacheKeyGenerator implements KeyGenerator {
Logger logger = Logger(MyCacheKeyGenerator.class);
private final static String SEPARATE = ":";
@Override
public Object generate(Object target, Method method, params) {
String className = Class().getName();
String methodName = Name();
String paramNames = "";
if(null != params) {
paramNames = JSONString(params);
}
String key = generate(className, methodName, paramNames);
logger.info("generate -> "+ key);
return key;
}
public static String generate(String clsName, String methodName, String params) {
StringBuilder sb = new StringBuilder();
sb.append(clsName);
sb.append(SEPARATE);
sb.append(methodName);
if(!StringUtils.isEmpty(params)) {
sb.append(SEPARATE);
sb.append(params);
}
String();
}
}
⾃定义RedisCacheManager
import org.dis.cache.CacheKeyPrefix;
import org.dis.cache.RedisCache;
import org.dis.cache.RedisCacheConfiguration;
import org.dis.cache.RedisCacheManager;
import org.dis.cache.RedisCacheWriter;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
public class RedisCacheManagerCustomize extends RedisCacheManager {
private final static String PREFIX = "bart:spring:cache:";
public final static CacheKeyPrefix cacheKeyPrefix = new CacheKeyPrefix() {
@Override
public String compute(String cacheName) {
return PREFIX;
}
};
protected final static Map<String, Duration> CACHE_NAME_MAP = new HashMap<>();
public RedisCacheManagerCustomize(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
ateRedisCache(name, copyCacheConfiguration(name, cacheConfig));
}
protected RedisCacheConfiguration copyCacheConfiguration(String name, RedisCacheConfiguration cacheConfig) {
if(null != cacheConfig) {
if(CACHE_ainsKey(name)) {
RedisCacheConfiguration redisCacheConfigurationCopy = Ttl(CACHE_(name))
putePrefixWith(RedisCacheManagerCustomize.cacheKeyPrefix);
return redisCacheConfigurationCopy;
}
}
return cacheConfig;
}
}
动态修改注解的值
什么要放到BeanDefinitionRegistryPostProcessor中去处理,因为此时所有的bean已经被spring扫描但是还未被初始化,正好适合修改注解的值,如果放到BeanPostProcessor中的话类可能已经被初始化了,此时修改注解⽆效,这⾥具体的原因要追踪spring源码。
import com.alibaba.fastjson.JSON;
import fig.cache.helper.CacheExpire;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.fig.BeanDefinition;
import org.springframework.fig.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.lang.annotation.Annotation;
import flect.Field;
import flect.InvocationHandler;
import flect.Method;
import flect.Proxy;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 在Bean创建之前动态修改注解的值
*
* 调⽤栈(由下到上):
* t.support.PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors(java.util.Collection, org.springframework.beans.factory.support.BeanDefinitionRegistry) * org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(org.springframework.beans.factory.support.BeanDefinitionRegistry)
* t.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.fig.ConfigurableListableBeanFactory, java.util.List)
* t.support.AbstractApplicationContext#refresh()
*/
@Component
public class AnnotationInjectProcessor implements BeanDefinitionRegistryPostProcessor {
protected final static Logger logger = Logger(AnnotationInjectProcessor.class);
private String keyGeneratorName = "";
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
// 需要处理的包名,只需要处理当前项⽬扫描路径和 @SpringBootApplication 配置的 scanBasePackages
List<String> projectScanPackageNames = new ArrayList<>();
String mainClassName = null; // ⼊⼝类名、
// 参考代码: org.springframework.boot.SpringApplication.deduceMainApplicationClass
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (StackTraceElement stackTraceElement : stackTraceElements) {
if("main".MethodName())) {
mainClassName = ClassName();
break;
}
}
String basePackageName = mainClassName.substring(0, mainClassName.lastIndexOf(".")); // 当前项⽬包名
projectScanPackageNames.add(basePackageName);
try {
Class<?> mainClass = Class.forName(mainClassName);
SpringBootApplication springBootApplication = Annotation(SpringBootApplication.class);
String[] scanBasePackages = springBootApplication.scanBasePackages();
if(null != scanBasePackages && scanBasePackages.length > 0) {
projectScanPackageNames.addAll(Arrays.asList(scanBasePackages));
}
} catch (Exception e) {
logger.info("get main class err, class = {}, reason = ", mainClassName, e);
}
String[] beanDefinitionNames = BeanDefinitionNames();
// 到⾃定义的key generator
List<Class<?>> prepareToInjectList = new ArrayList<>(beanDefinitionNames.length);
for (String beanDefinitionName : beanDefinitionNames) {
BeanDefinition beanDefinition = BeanDefinition(beanDefinitionName);
String beanClassName = BeanClassName();
try {
// 如果为空或者当前类就跳过
if(StringUtils.isEmpty(beanClassName) || Class().getName().equals(beanClassName)) {
continue;
}
Class<?> cls = Class.forName(beanClassName);
if(KeyGenerator.class.isAssignableFrom(cls)) {
keyGeneratorName = beanDefinitionName;
}
for (String scanPackageName : projectScanPackageNames) {
if(beanClassName.startsWith(scanPackageName)) {
prepareToInjectList.add(cls);
break;
}
}
}catch (Exception e) {
<("can not load class = {}, reason: {}", beanClassName, e);
}
}
// 当前环境必须有⼀个key generator 否则报错
Assert.isTrue(!StringUtils.isEmpty(keyGeneratorName),
"current ioc environment must have one org.springframework.cache.interceptor.KeyGenerator instance!");
// 开始修改注解的值
for (Class<?> cls : prepareToInjectList) {
injectAnnotationValue(cls, keyGeneratorName );
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
/**
* 修改当前类的 @Cacheable 、@CachePut 注解的属性值
* @param cls
*/
protected static void injectAnnotationValue(Class<?> cls, String keyGeneratorName) {
CacheConfig cacheConfig = Annotation(CacheConfig.class);
if(null != cacheConfig && cacheConfig.cacheNames().length > 0 && !StringUtils.isEmpty(cacheConfig.keyGenerator())) {
CacheExpire cacheExpire = Annotation(CacheExpire.class);
if(null != cacheExpire) {
RedisCacheManagerCustomize.CACHE_NAME_MAP.put(cacheConfig.cacheNames()[0], Duration.ofSeconds(cacheExpire.unit().l())));
}
return; // 如果当前类通过@CacheConfig指定了cacheNames、kenGenerator就不处理
}
Method[] declaredMethods = DeclaredMethods();
for (Method method : declaredMethods) {
InvocationHandler handler = null ;
try {
Object annotation = Annotation(Cacheable.class);
if(null == annotation) {
annotation = Annotation(CachePut.class);
}
if(null == annotation) {
annotation = Annotation(CacheEvict.class);
}
if(null == annotation) {
return;
}
handler = InvocationHandler(annotation);
if(null != handler) {
injectAnnotationValue(cls, method, handler, keyGeneratorName);
}
} catch (Exception e) {
<("inject error : class=[{}] , method=[{}] ! reason : {}", Name(), Name(), e);
}
}
}
protected static void injectAnnotationValue(Class<?> cls, Method method ,InvocationHandler handler, String keyGeneratorName) throws Exception {
// 获取 AnnotationInvocationHandler 的 memberValues 字段
Field typeField = Class().getDeclaredField("type");
ReflectionUtils.makeAccessible(typeField);
String annotationTypeName = ((Class<? extends Annotation>)(handler)).getName();
Field memberValuesField = Class().getDeclaredField("memberValues");
ReflectionUtils.makeAccessible(memberValuesField);
Map<String, Object> memberValues = (Map<String, Object>)(handler);
logger.debug("inject start class=[{}] , method=[{}], annotation=[{}] , memberValues={}", Name(), Name(), annotationTypeName, JSONString(memberValues)); String[] cacheNames = (String[])("cacheNames");
String generateKey = Name(), Name(), "");
if(cacheNames.length == 0) {
memberValues.put("cacheNames", new String[]{generateKey});
}
String keyGenerator = (("keyGenerator");
// 指定的key和keyGenerator会冲突,所以判断⼀下不能影响框架之前的逻辑
if(StringUtils.("key")) && StringUtils.isEmpty(keyGenerator) ) {
memberValues.put("keyGenerator", keyGeneratorName);
}
// 获得@CacheExpire注解解析失效时间
CacheExpire cacheExpire = Annotation(CacheExpire.class);
if(null == cacheExpire) {
// ⽅法未添加就取当前类的注解
cacheExpire = Annotation(CacheExpire.class);
}
if(null != cacheExpire) {
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论