Spring Boot自定义Redis缓存配置,保存value格式JSON字符串

时间:2021-08-20 14:57:43

Spring Boot自定义Redis缓存,保存格式JSON字符串

部分内容转自 https://blog.csdn.net/caojidasabi/article/details/83059642

package springboot01cache.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import springboot01cache.bean.Student; import java.net.UnknownHostException;
import java.time.Duration; @Configuration
public class MyRedisConfig
{ //自定义RedisTemplate
@Bean
public RedisTemplate<Object, Student> student_redis_template(RedisConnectionFactory redisConnectionFactory)
{
RedisTemplate<Object, Student> template = new RedisTemplate<Object, Student>();
template.setConnectionFactory(redisConnectionFactory);
//使用JSON格式的序列化,保存
Jackson2JsonRedisSerializer<Student> serializer = new Jackson2JsonRedisSerializer<Student>(Student.class);
template.setDefaultSerializer(serializer);
return template;
} //自定义cacheManager缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory)
{
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om); //配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ZERO)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
} }

自定义Redis配置