Problems encountered in SpringBoot 2.3.5 Integrating redis cache custom JSON serialization.

Keywords: Redis JSON SpringBoot JDK

Currently, I am learning springboot from teacher Lei Fengyang in Silicon Valley.
The springboot version used in the teacher's course is 1.5, while I use 2.3.5.
The difference between the 2.x and 1.x versions of springboot is quite significant, with many of the underlying code changed and quite a bit changed.
Currently, I am learning to customize JSON serialization using redis cache, and I have encountered a very different problem between 2.x bottom source configuration customized JSON sequence elements and 1.x (taught in Teacher Ray's course).
After spending a lot of time in Baidu, after trying n methods, I finally found a feasible method, so that I can record it for other friends who have encountered this problem and reuse in the future.

I refer to this great god's article: https://blog.csdn.net/weixin_44757206/article/details/106407916
One of the most critical is to configure the redis configuration class to customize JSON serialization, code as follows: I have also written in the package that I imported.

package com.atguigu.cache.config;

import com.atguigu.cache.bean.Employee;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;
import java.time.Duration;

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Employee> EmpRedisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(serializer);
        return template;
    }

    //CacheManager Customizers can customize some rules for caching
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(1))
                .disableCachingNullValues()
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();}
}

It's possible to do this by hand, but there's also a small pit where I've been stuck for almost half an hour.
If you have not previously configured a custom acheManager, the default configuration will be used, serialized using Jdk, and stored in redis.
In the case of previous operations, this record will be retained in redis, and when run again, an error will be reported, with the following error information:
Failed to complete request: org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unexpected character ('¬' (code 172)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
The reason for this error is that the cache failed because a value serialized by default jdk was previously cached in redis with the key currently in use.
Just serialize the default jdk previously cached with this key into redis and delete it.
Looking back now, the simple steps jammed me for over an hour.
So I decided to write this article, because after all, good memory is not as good as bad writing, and it is also convenient for other friends who are learning springboot!

Posted by rantsh on Wed, 24 Jun 2020 18:31:20 -0700