1
1
package com .springboot .springbootredis .config ;
2
2
3
+ import com .fasterxml .jackson .annotation .JsonAutoDetect ;
4
+ import com .fasterxml .jackson .annotation .PropertyAccessor ;
5
+ import com .fasterxml .jackson .databind .ObjectMapper ;
3
6
import org .springframework .boot .autoconfigure .AutoConfigureAfter ;
4
7
import org .springframework .boot .autoconfigure .data .redis .RedisAutoConfiguration ;
8
+ import org .springframework .cache .CacheManager ;
5
9
import org .springframework .context .annotation .Bean ;
6
10
import org .springframework .context .annotation .Configuration ;
11
+ import org .springframework .data .redis .cache .RedisCacheConfiguration ;
12
+ import org .springframework .data .redis .cache .RedisCacheManager ;
13
+ import org .springframework .data .redis .cache .RedisCacheWriter ;
14
+ import org .springframework .data .redis .connection .RedisConnectionFactory ;
7
15
import org .springframework .data .redis .connection .lettuce .LettuceConnectionFactory ;
8
16
import org .springframework .data .redis .core .RedisTemplate ;
9
17
import org .springframework .data .redis .serializer .GenericJackson2JsonRedisSerializer ;
18
+ import org .springframework .data .redis .serializer .Jackson2JsonRedisSerializer ;
19
+ import org .springframework .data .redis .serializer .RedisSerializationContext ;
10
20
import org .springframework .data .redis .serializer .StringRedisSerializer ;
11
21
12
22
import java .io .Serializable ;
23
+ import java .time .Duration ;
13
24
14
25
/**
15
26
* @Version: 1.0
@@ -27,4 +38,30 @@ public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionF
27
38
template .setConnectionFactory (redisConnectionFactory );
28
39
return template ;
29
40
}
41
+
42
+ @ Bean
43
+ public CacheManager cacheManager (RedisConnectionFactory redisConnectionFactory ) {
44
+ return new RedisCacheManager (
45
+ RedisCacheWriter .nonLockingRedisCacheWriter (redisConnectionFactory ),
46
+ this .getRedisCacheConfigurationWithTtl (600 ) // 默认策略,未配置的 key 会使用这个
47
+ );
48
+ }
49
+
50
+ private RedisCacheConfiguration getRedisCacheConfigurationWithTtl (Integer seconds ) {
51
+ Jackson2JsonRedisSerializer <Object > jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer <>(Object .class );
52
+ ObjectMapper om = new ObjectMapper ();
53
+ om .setVisibility (PropertyAccessor .ALL , JsonAutoDetect .Visibility .ANY );
54
+ om .enableDefaultTyping (ObjectMapper .DefaultTyping .NON_FINAL );
55
+ jackson2JsonRedisSerializer .setObjectMapper (om );
56
+
57
+ RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration .defaultCacheConfig ();
58
+ redisCacheConfiguration = redisCacheConfiguration .serializeValuesWith (
59
+ RedisSerializationContext
60
+ .SerializationPair
61
+ .fromSerializer (jackson2JsonRedisSerializer )
62
+ ).entryTtl (Duration .ofSeconds (seconds ));
63
+
64
+ return redisCacheConfiguration ;
65
+ }
66
+
30
67
}
0 commit comments