### 添加以下配置信息; ```java /** * 基于注解添加缓存 */ @Configuration @EnableCaching public class CacheConfig extends CachingConfigurerSupport { private final RedisConnectionFactory redisConnectionFactory; CacheConfig(RedisConnectionFactory redisConnectionFactory) { this.redisConnectionFactory = redisConnectionFactory; } @Bean @Override public KeyGenerator keyGenerator() { return (o, method, objects) -> { StringBuilder sb = new StringBuilder(32); sb.append(o.getClass().getSimpleName()); sb.append("."); sb.append(method.getName()); if (objects.length > 0) { sb.append("#"); } String sp = ""; for (Object object : objects) { sb.append(sp); if (object == null) { sb.append("NULL"); } else { sb.append(object.toString()); } sp = "."; } return sb.toString(); }; } /** * 配置 RedisCacheManager,使用 cache 注解管理 redis 缓存 */ @Bean @Override public CacheManager cacheManager() { // 初始化一个RedisCacheWriter RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); // 设置默认过期时间:30 分钟 RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(30)) // .disableCachingNullValues() // 使用注解时的序列化、反序列化 .serializeKeysWith(MyRedisCacheManager.STRING_PAIR) .serializeValuesWith(MyRedisCacheManager.FASTJSON_PAIR); return new MyRedisCacheManager(cacheWriter, defaultCacheConfig); } } ``` #### `redis`配置信息: ```java @Configuration @ConditionalOnClass(RedisOperations.class) @EnableConfigurationProperties(RedisProperties.class) @Import({LettuceConnectionConfiguration.class}) public class RedisConfig { @Bean @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate */ public static final GenericFastJsonRedisSerializer FASTJSON_SERIALIZER = new GenericFastJsonRedisSerializer(); /** * key serializer pair */ public static final RedisSerializationContext.SerializationPair STRING_PAIR = RedisSerializationContext .SerializationPair.fromSerializer(STRING_SERIALIZER); /** * value serializer pair */ public static final RedisSerializationContext.SerializationPair
基于springboot2.x集成缓存注解及设置过期时间
内容版权声明:除非注明,否则皆为本站原创文章。