踩坑,springboot2.x整合redis序列化
阿新 • • 發佈:2020-08-03
package com.ws.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.ws.pojo.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.*; import org.springframework.util.Assert; import java.net.UnknownHostException; import java.time.Duration; @Configuration public class MyRedisConfig { @Bean public RedisTemplate<Object, Employee> myredisTemplate(RedisConnectionFactory redisConnectionFactory) throwsUnknownHostException { RedisTemplate<Object, Employee> template = new RedisTemplate(); template.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer<Employee> serializer = new Jackson2JsonRedisSerializer<>(Employee.class); template.setDefaultSerializer(serializer); return template; } @Bean RedisCacheManager employeeRedisCacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Employee.class))) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer(Employee.class))) .disableCachingNullValues();
RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(config) .transactionAware() .build(); return redisCacheManager; } }
純粹是怕自己忘記所以才寫的