zoukankan      html  css  js  c++  java
  • 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值的时候调用我重写的逻辑,拿到当前方法的cacheNamesMap<String, Duration> 取对应的失效时间从而实现了方法级别的粒度控制。

    步骤

    依赖

    <project xmlns="http://maven.apache.org/POM/4.0.0"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/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>
    		<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    		<maven.compiler.target>1.8</maven.compiler.target>
    		<maven.compiler.source>1.8</maven.compiler.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>
    			<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 java.util.concurrent.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 java.lang.reflect.Method;
    
    /**
     * Created by BartG on 2019/1/23.
     * 自定义的缓存key生成器
     */
    @Component("myCacheKeyGenerator")
    public class MyCacheKeyGenerator implements KeyGenerator {
    
        Logger logger = LoggerFactory.getLogger(MyCacheKeyGenerator.class);
    
        private final static String SEPARATE = ":";
    
        @Override
        public Object generate(Object target, Method method, Object... params) {
            String className = target.getClass().getName();
            String methodName = method.getName();
            String paramNames = "";
            if(null != params) {
                paramNames = JSON.toJSONString(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);
            }
            return sb.toString();
        }
    }
    

    自定义RedisCacheManager

    
    import org.springframework.data.redis.cache.CacheKeyPrefix;
    import org.springframework.data.redis.cache.RedisCache;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.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) {
            return super.createRedisCache(name, copyCacheConfiguration(name, cacheConfig));
        }
    
        protected RedisCacheConfiguration copyCacheConfiguration(String name, RedisCacheConfiguration cacheConfig) {
            if(null != cacheConfig) {
                if(CACHE_NAME_MAP.containsKey(name)) {
                    RedisCacheConfiguration redisCacheConfigurationCopy = cacheConfig.entryTtl(CACHE_NAME_MAP.get(name))
                    		.computePrefixWith(RedisCacheManagerCustomize.cacheKeyPrefix);
                    return redisCacheConfigurationCopy;
                }
            }
            return cacheConfig;
        }
    
    }
    

    动态修改注解的值

    什么要放到 BeanDefinitionRegistryPostProcessor 中去处理,因为此时所有的bean已经被spring扫描但是还未被初始化,正好适合修改注解的值,如果放到BeanPostProcessor 中的话类可能已经被初始化了,此时修改注解无效,这里具体的原因要追踪spring源码。

    
    import com.alibaba.fastjson.JSON;
    import com.spboot.config.cache.helper.CacheExpire;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanDefinition;
    import org.springframework.beans.factory.config.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 java.lang.reflect.Field;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.time.Duration;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 在Bean创建之前动态修改注解的值
     *
     * 调用栈(由下到上):
     * org.springframework.context.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)
     * org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
     * org.springframework.context.support.AbstractApplicationContext#refresh()
     */
    @Component
    public class AnnotationInjectProcessor implements BeanDefinitionRegistryPostProcessor {
    
        protected final static Logger logger = LoggerFactory.getLogger(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".equals(stackTraceElement.getMethodName())) {
                    mainClassName = stackTraceElement.getClassName();
                    break;
                }
            }
            Assert.notNull(mainClassName, "未找到入口类,程序异常!");
            String basePackageName = mainClassName.substring(0, mainClassName.lastIndexOf(".")); // 当前项目包名
            projectScanPackageNames.add(basePackageName);
            try {
                Class<?> mainClass = Class.forName(mainClassName);
                SpringBootApplication springBootApplication = mainClass.getAnnotation(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 = registry.getBeanDefinitionNames();
            // 找到自定义的key generator
            List<Class<?>> prepareToInjectList = new ArrayList<>(beanDefinitionNames.length);
            for (String beanDefinitionName : beanDefinitionNames) {
                BeanDefinition beanDefinition = registry.getBeanDefinition(beanDefinitionName);
                String beanClassName = beanDefinition.getBeanClassName();
                try {
                    // 如果为空或者当前类就跳过
                    if(StringUtils.isEmpty(beanClassName) || this.getClass().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) {
                    logger.error("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 = cls.getAnnotation(CacheConfig.class);
            if(null != cacheConfig && cacheConfig.cacheNames().length > 0 && !StringUtils.isEmpty(cacheConfig.keyGenerator())) {
                CacheExpire cacheExpire = cls.getAnnotation(CacheExpire.class);
                if(null != cacheExpire) {
                    RedisCacheManagerCustomize.CACHE_NAME_MAP.put(cacheConfig.cacheNames()[0], Duration.ofSeconds(cacheExpire.unit().toSeconds(cacheExpire.ttl())));
                }
                return; // 如果当前类通过@CacheConfig指定了cacheNames、kenGenerator就不处理
            }
            Method[] declaredMethods = cls.getDeclaredMethods();
            for (Method method : declaredMethods) {
                InvocationHandler handler = null ;
                try {
                    Object annotation = method.getAnnotation(Cacheable.class);
                    if(null == annotation) {
                        annotation = method.getAnnotation(CachePut.class);
                    }
                    if(null == annotation) {
                        annotation = method.getAnnotation(CacheEvict.class);
                    }
                    if(null == annotation) {
                        return;
                    }
                    handler = Proxy.getInvocationHandler(annotation);
                    if(null != handler) {
                        injectAnnotationValue(cls, method, handler, keyGeneratorName);
                    }
                } catch (Exception e) {
                    logger.error("inject error : class=[{}] , method=[{}]  ! reason : {}", cls.getName(), method.getName(), e);
                }
            }
        }
    
        protected static void injectAnnotationValue(Class<?> cls, Method method ,InvocationHandler handler,  String keyGeneratorName) throws Exception {
            // 获取 AnnotationInvocationHandler 的 memberValues 字段
            Field typeField = handler.getClass().getDeclaredField("type");
            ReflectionUtils.makeAccessible(typeField);
            String annotationTypeName = ((Class<? extends Annotation>)typeField.get(handler)).getName();
            Field memberValuesField = handler.getClass().getDeclaredField("memberValues");
            ReflectionUtils.makeAccessible(memberValuesField);
            Map<String, Object> memberValues = (Map<String, Object>)memberValuesField.get(handler);
            logger.debug("inject start class=[{}] , method=[{}], annotation=[{}] , memberValues={}", cls.getName(), method.getName(), annotationTypeName, JSON.toJSONString(memberValues));
            String[] cacheNames = (String[])memberValues.get("cacheNames");
            String generateKey = MyCacheKeyGenerator.generate(cls.getName(), method.getName(), "");
            if(cacheNames.length == 0) {
                memberValues.put("cacheNames", new String[]{generateKey});
            }
            String keyGenerator = (String)memberValues.get("keyGenerator");
            // 指定的key和keyGenerator会冲突,所以判断一下不能影响框架之前的逻辑
            if(StringUtils.isEmpty(memberValues.get("key")) && StringUtils.isEmpty(keyGenerator) ) {
                memberValues.put("keyGenerator", keyGeneratorName);
            }
            // 获得@CacheExpire注解解析失效时间
            CacheExpire cacheExpire = method.getAnnotation(CacheExpire.class);
            if(null == cacheExpire) {
                // 方法未添加就取当前类的注解
                cacheExpire = cls.getAnnotation(CacheExpire.class);
            }
            if(null != cacheExpire) {
                RedisCacheManagerCustomize.CACHE_NAME_MAP.put(generateKey, Duration.ofSeconds(cacheExpire.unit().toSeconds(cacheExpire.ttl())));
            }
            logger.debug("inject end class=[{}] , method=[{}], annotation=[{}] , memberValues={}", cls.getName(), method.getName(), annotationTypeName, JSON.toJSONString(memberValues));
        }
    
    }
    

    配置类

    
    import java.time.Duration;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    
    import com.fasterxml.jackson.databind.module.SimpleModule;
    import com.spboot.config.mvc.JsonConverters;
    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializationContext;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    @Configuration
    @EnableCaching // 开启spring的缓存
    public class CacheConfig {
    
        
    
        /**
         * 自定义得缓存管理器
         * @param redisConnectionFactory
         * @return
         */
        @Primary
        @Bean
        public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
            //初始化一个RedisCacheWriter
            RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
            // key 序列化方式
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
            // value的序列化机制
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = jackson2JsonRedisSerializer();
            // 配置
            RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofHours(1))
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer))  // 设置 k v 序列化机制
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                    .computePrefixWith(RedisCacheManagerCustomize.cacheKeyPrefix);
            //初始化RedisCacheManager
    //        RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
            RedisCacheManager cacheManager = new RedisCacheManagerCustomize(redisCacheWriter, defaultCacheConfig);
            return cacheManager;
        }
        
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
            Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            SimpleModule module = new SimpleModule();
            // 添加对自定义日期类型解析的解析器
            module.addSerializer(LocalDateTime.class, JsonConverters.localDateTimeSerializer());
            module.addDeserializer(LocalDateTime.class, JsonConverters.localDateTimeDeserializer());
            module.addSerializer(LocalDate.class, JsonConverters.localDateSerializer());
            module.addDeserializer(LocalDate.class, JsonConverters.localDateDeserializer());
            jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
            return jackson2JsonRedisSerializer;
        }
    
    
    }
    

    JSON序列化器

    
    import java.io.IOException;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.Locale;
    
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.core.JsonParser;
    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.DeserializationContext;
    import com.fasterxml.jackson.databind.JsonDeserializer;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
    
    
    public class JsonConverters {
    
    	final static DateTimeFormatter DTF_LOCADATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    	final static DateTimeFormatter DTF_LOCADATE = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
    
    	public static JsonDeserializer<LocalDate> localDateDeserializer() {
    		return new JsonDeserializer<LocalDate>() {
    			@Override
    			public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    				String result = StringDeserializer.instance.deserialize(p, ctxt);
    				System.out.println("LocalDateTimeJsonDeserializer -> "+ result);
    				return LocalDate.parse(result, DTF_LOCADATE);
    			}
    		};
    	}
    	
    	public static JsonSerializer<LocalDate> localDateSerializer() {
    		return new JsonSerializer<LocalDate>() {
    			@Override
    			public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    				String format = DTF_LOCADATE.format(value);
    				System.out.println("LocalDateTimeJsonSerializer -> "+ format);
    				gen.writeString(format);
    //			gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    			}
    		};
    	}
    
    	public static JsonDeserializer<LocalDateTime> localDateTimeDeserializer() {
    		return new JsonDeserializer<LocalDateTime>() {
    			@Override
    			public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    				String result = StringDeserializer.instance.deserialize(p, ctxt);
    				System.out.println("LocalDateTimeJsonDeserializer -> "+ result);
    				return LocalDateTime.parse(result, DTF_LOCADATETIME);
    			}
    		};
    	}
    
    	public static JsonSerializer<LocalDateTime> localDateTimeSerializer() {
    		return new JsonSerializer<LocalDateTime>() {
    			@Override
    			public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    				String format = DTF_LOCADATETIME.format(value);
    				System.out.println("LocalDateTimeJsonSerializer -> "+ format);
    				gen.writeString(format);
    //			gen.writeNumber(value.toInstant(ZoneOffset.of("+8")).toEpochMilli());
    			}
    		};
    	}
    }
    

    测试类

    controller

    
    import java.util.HashMap;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/api")
    public class TestApiController {
    
    	@Autowired
    	TestApiService testApiService;
    	
        // 使用全局缓存命名空间
    	@GetMapping("/v10")
    	public ResponseEntity v10() {
    		System.err.println("线程 = "+ Thread.currentThread().getId());
    		System.err.println("类加载器 = "+ this.getClass().getClassLoader());
    		return ResponseEntity.ok(new HashMap<String, Object>(){{
    			put("code", 0);
    			put("msg", "ok");
    			put("data", testApiService.data_v1());
    		}});
    	}
    	
    }
    

    service

    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    
    import com.spboot.config.cache.helper.CacheExpire;
    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.stereotype.Service;
    
    //全局失效时间
    @CacheExpire(ttl = 1, unit = TimeUnit.MINUTES)
    @Service
    public class TestApiService {
    
        //方法级别失效时间
    	@CacheExpire(ttl = 10, unit = TimeUnit.SECONDS)
    	@Cacheable
    	public Map<String,String> data_v1() {
    		Map<String,String> map = new HashMap<String, String>();
    		map.put("k1", "v1");
    		map.put("k2", "v2");
    		map.put("k3", "v3");
    		return map;
    	}
    	
    }
    

    启动类

    import org.springframework.boot.SpringApplication;  
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication 
    public class Application {
        public static void main(String[] args) {  
            SpringApplication.run(Application.class, args);
        }  
    } 
    

    测试接口

    项目启动后调用http://localhost:8888/api/v10

    进入redis-cli查看key以及对应的失效时间:

    27.0.0.1:6379> keys *
    1) "bart:spring:cache:com.spboot.api.TestApiService:data_v1:[]"
    
    27.0.0.1:6379> ttl "bart:spring:cache:com.spboot.api.TestApiService:data_v1:[]"
    (integer) 10 # 这里手速要快,因为失效时间只有10秒钟
    

    如果redis中缓存key对应的失效时间确实是@CacheExpire配置的失效时间说明是好的。

  • 相关阅读:
    解决MVC的Controller和Web API的Controller类名不能相同的问题
    SSO的踢人模式/禁入模式
    os处理文件
    pyton mock
    python xml转换成json
    python调用jpype
    Python程序的执行过程原理(解释型语言和编译型语言)
    python 字典、列表、字符串 之间的转换
    python接口自动化1
    不用框架,原生使用python做注册接口/登陆接口/充值接口的测试,做的数据/代码分离
  • 原文地址:https://www.cnblogs.com/bartggg/p/15717748.html
Copyright © 2011-2022 走看看