Spring Boot自定义Redis缓存配置,保存value格式JSON字符串
Posted taopanfeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot自定义Redis缓存配置,保存value格式JSON字符串相关的知识,希望对你有一定的参考价值。
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;
以上是关于Spring Boot自定义Redis缓存配置,保存value格式JSON字符串的主要内容,如果未能解决你的问题,请参考以下文章
Spring boot 拾遗 —— Spring Cache 使用 Jackson 与 自定义 TTL
Intellij IDEA 搭建Spring Boot项目配置事务和Redis缓存