springboot(24)ehcache自定义CacheManager

springboot 1.5.x

1
2
3
4
5
6
7
8
@Bean
public CacheManager cacheManager(RedisTemplate<String,?> redisTemplate) {
RedisCacheManager cacheManager= new RedisCacheManager(redisTemplate);
// 开启使用缓存名称最为key前缀
cacheManager.setUsePrefix(true);
cacheManager.setDefaultExpiration(60);
return cacheManager;
}

springboot 2.0.x

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// 使用fastjson序列化替代jdk序列化
RedisSerializationContext.SerializationPair serializationPair =
RedisSerializationContext.SerializationPair.fromSerializer(getRedisSerializer());
// 设置缓存有效期一小时
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofHours(1)).serializeKeysWith(serializationPair)
.serializeValuesWith(serializationPair);
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}

private RedisSerializer<Object> getRedisSerializer(){
return new GenericFastJsonRedisSerializer();
}