|
5 | 5 | import com.fasterxml.jackson.annotation.PropertyAccessor;
|
6 | 6 | import com.fasterxml.jackson.databind.ObjectMapper;
|
7 | 7 | import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import org.springframework.cache.CacheManager; |
8 | 10 | import org.springframework.cache.annotation.CachingConfigurerSupport;
|
9 | 11 | import org.springframework.cache.annotation.EnableCaching;
|
10 | 12 | import org.springframework.context.annotation.Bean;
|
|
20 | 22 | import org.springframework.data.redis.serializer.StringRedisSerializer;
|
21 | 23 |
|
22 | 24 | import java.time.Duration;
|
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.Map; |
23 | 27 |
|
24 | 28 | /**
|
25 | 29 | * Redis配置类
|
26 | 30 | * Created by zhanglei on 2020/3/2.
|
27 | 31 | */
|
28 | 32 | @EnableCaching
|
29 | 33 | @Configuration
|
| 34 | +@Slf4j |
30 | 35 | public class RedisConfig extends CachingConfigurerSupport {
|
31 | 36 |
|
32 | 37 | @Bean
|
@@ -67,12 +72,22 @@ public RedisSerializer<Object> redisSerializer() {
|
67 | 72 | }
|
68 | 73 |
|
69 | 74 | @Bean
|
70 |
| - public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { |
71 |
| - RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); |
72 |
| - //设置Redis缓存有效期为1天 |
73 |
| - RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() |
74 |
| - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1)); |
75 |
| - return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); |
| 75 | + public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { |
| 76 | + RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig() |
| 77 | + .entryTtl(Duration.ofDays(1)) // 默认没有特殊指定的 |
| 78 | + .computePrefixWith(cacheName -> "caching:" + cacheName); |
| 79 | + |
| 80 | + // 针对不同cacheName,设置不同的过期时间 |
| 81 | + Map<String, RedisCacheConfiguration> initialCacheConfiguration = new HashMap<String, RedisCacheConfiguration>() {{ |
| 82 | + put("demoCache", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMillis(20*1000))); |
| 83 | + // ... |
| 84 | + }}; |
| 85 | + |
| 86 | + RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory) |
| 87 | + .cacheDefaults(defaultCacheConfig) // 默认配置(强烈建议配置上)。 比如动态创建出来的都会走此默认配置 |
| 88 | + .withInitialCacheConfigurations(initialCacheConfiguration) // 不同cache的个性化配置 |
| 89 | + .build(); |
| 90 | + return redisCacheManager; |
76 | 91 | }
|
77 | 92 |
|
78 | 93 | }
|
0 commit comments