package com.newfiber.config; 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.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig{ @Bean("redisTemplate") public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){ //1、创建RedisTemplate对象 RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); //2、添加Redis的连接工厂 redisTemplate.setConnectionFactory(factory); //3、定义Jackson2的序列化对象 Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); //4、指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); jsonRedisSerializer.setObjectMapper(om); //5、String的序列化方式 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //6、配置key 以及 hashkey的序列化方式 redisTemplate.setKeySerializer(stringRedisSerializer); redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setValueSerializer(jsonRedisSerializer); redisTemplate.setHashValueSerializer(jsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }