package com.terra.common.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.terra.common.entity.all.FastJson2JsonRedisSerializer; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.cache.Cache; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.StringRedisSerializer; import java.util.HashMap; import java.util.Map; /** * Redis配置类 * @author WWW */ @Configuration @SuppressWarnings("ALL") @AutoConfigureBefore(RedisAutoConfiguration.class) public class RedisConfig extends CachingConfigurerSupport { /** * 配置自定义redisTemplate */ @Bean @SuppressWarnings(value = { "unchecked", "rawtypes" }) public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(factory); //Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer<>(Object.class); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); template.setKeySerializer(new StringRedisSerializer()); //template.setValueSerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); template.afterPropertiesSet(); return template; } @Bean @Override public CacheErrorHandler errorHandler() { // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 return new CacheErrorHandler() { @Override public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { Map error = new HashMap(3); error.put("e", e); error.put("cache", cache); error.put("key", key); } @Override public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { Map error = new HashMap(4); error.put("e", e); error.put("cache", cache); error.put("key", key); error.put("value", value); } @Override public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { Map error = new HashMap(3); error.put("e", e); error.put("cache", cache); error.put("key", key); } @Override public void handleCacheClearError(RuntimeException e, Cache cache) { Map error = new HashMap(2); error.put("e", e); error.put("cache", cache); } }; } }