Springboot-2.0 version of custom ReidsCacheManager changes

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 RedisTemplateas a parameter to customize CacheManager.

Let's take a look at the difference between the two versions:

Version 1.0 CacheManager constructor

img_73b813405fec4738f7d682c11c3efb6e.png

Version 2.0 CacheManager constructor

img_dcf19672d9b26050fdfc72f3f1ecb640.png

RedisCacheWriterProvides 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.

RedisCacheConfigurationAccording 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, CacheManagerthe 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.

Published 81 original articles · Like1 · Visits 30,000+

Guess you like

Origin blog.csdn.net/xiaoanzi123/article/details/105432174