Springboot-2.0 version of custom ReidsCacheManager changes
Reprinted article address: https://yq.aliyun.com/articles/650194 [Learn to reprint and use, if you have any questions, please contact me to delete]
1. Problem Discovery
In version 1.0, we configure redis cacheManager in this way:
//缓存管理器
@Bean
public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
cacheManager.setDefaultExpiration(10000);
return cacheManager;
} //缓存管理器
However, in the 2.0 version, this code directly reported an error because the RedisCacheManager canceled the public RedisCacheManager(RedisOperations redisOperations)
construction method in the 1.0 version , so we can no longer use it RedisTemplate
as a parameter to customize CacheManager
.
Let's take a look at the difference between the two versions:
Version 1.0 CacheManager constructor
Version 2.0 CacheManager constructor
RedisCacheWriter
Provides access to Redis set, setnx, get and other commands, can be shared by multiple caches, and is responsible for writing / reading binary data from Redis.
RedisCacheConfiguration
According to the name, it can be thought of as providing redis configuration.
2. CacheManager custom configuration in springboot2.0
/**
* 缓存管理器
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
//设置默认超过期时间是30秒
defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
//初始化RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
In the above code, CacheManager
the value serialization method is also set , so with this configuration, you can directly implement redis storage of json in the form of annotations without having to write more configuration.