content: package com.weiguanjishu.common;
  
  import com.fasterxml.jackson.annotation.JsonAutoDetect;
  import com.fasterxml.jackson.annotation.PropertyAccessor;
  import com.fasterxml.jackson.databind.ObjectMapper;
  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.GenericJackson2JsonRedisSerializer;
  import org.springframework.data.redis.serializer.RedisSerializer;
  import org.springframework.data.redis.serializer.StringRedisSerializer;
  
  /**
   * @author 微信公众号：微观技术
   */
  
  @Configuration
  public class RedisConfig {
  
      @Bean
      public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
          RedisTemplate<String, Object> template = new RedisTemplate<>();
          template.setConnectionFactory(factory);
  
          StringRedisSerializer stringSerializer = new StringRedisSerializer();
  
          RedisSerializer jacksonSerializer = getJacksonSerializer();
  
          template.setKeySerializer(stringSerializer);
          template.setValueSerializer(jacksonSerializer);
          template.setHashKeySerializer(stringSerializer);
          template.setHashValueSerializer(jacksonSerializer);
          template.setEnableTransactionSupport(true);
          template.afterPropertiesSet();
  
          return template;
      }
  
      private RedisSerializer getJacksonSerializer() {
          ObjectMapper om = new ObjectMapper();
          om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
          om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
          return new GenericJackson2JsonRedisSerializer(om);
      }
  
  }
  