1+ package com .springboot .cloud .sysadmin .organization .config ;
2+
3+ import com .fasterxml .jackson .annotation .JsonAutoDetect ;
4+ import com .fasterxml .jackson .annotation .PropertyAccessor ;
5+ import com .fasterxml .jackson .databind .ObjectMapper ;
6+ import org .springframework .cache .CacheManager ;
7+ import org .springframework .cache .annotation .CachingConfigurerSupport ;
8+ import org .springframework .cache .annotation .EnableCaching ;
9+ import org .springframework .context .annotation .Bean ;
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 ;
15+ import org .springframework .data .redis .core .RedisTemplate ;
16+ import org .springframework .data .redis .core .StringRedisTemplate ;
17+ import org .springframework .data .redis .serializer .Jackson2JsonRedisSerializer ;
18+
19+ import java .time .Duration ;
20+
21+ @ Configuration
22+ @ EnableCaching
23+ public class RedisConfig extends CachingConfigurerSupport {
24+
25+ @ Bean
26+ public RedisTemplate <String , String > redisTemplate (RedisConnectionFactory factory ) {
27+ ObjectMapper om = new ObjectMapper ();
28+ om .setVisibility (PropertyAccessor .ALL , JsonAutoDetect .Visibility .ANY );
29+ om .enableDefaultTyping (ObjectMapper .DefaultTyping .NON_FINAL );
30+ //redis序列化
31+ Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object .class );
32+ jackson2JsonRedisSerializer .setObjectMapper (om );
33+
34+ StringRedisTemplate template = new StringRedisTemplate (factory );
35+ template .setValueSerializer (jackson2JsonRedisSerializer );
36+ template .afterPropertiesSet ();
37+ return template ;
38+ }
39+
40+ @ Bean
41+ public CacheManager cacheManager (RedisTemplate redisTemplate ) {
42+ //全局redis缓存过期时间
43+ RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration .defaultCacheConfig ().entryTtl (Duration .ofDays (1 ));
44+ RedisCacheWriter redisCacheWriter = RedisCacheWriter .nonLockingRedisCacheWriter (redisTemplate .getConnectionFactory ());
45+ return new RedisCacheManager (redisCacheWriter , redisCacheConfiguration );
46+ }
47+ }
0 commit comments