@Configuration
public class RedisConfig {

	@Resource
	private RedisProperties redisProperties;

	@Value("${spring.redis.hotwheel.username}")
	private String          redisUserName;

	@Bean
	public <K,V> RedisTemplate<K,V> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
		lettuceConnectionFactory.validateConnection();
		RedisTemplate<K, V> template = new RedisTemplate();
		template.setConnectionFactory(lettuceConnectionFactory);
		template.setKeySerializer(new GenericToStringSerializer(Object.class));
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
		template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
		return template;
	}
}

线上问题:

org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized field "startCityName"

jackson序列化的时候,存在不认识的字段 会报错的问题,有以下两种解决方案

1,改用阿里的fastjson

2,jackson序列化默认存在不认识字段报错,用户可以自己设置忽略

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
new GenericJackson2JsonRedisSerializer(objectMapper)

更改后代码

@Configuration
public class RedisConfig {

	@Resource
	private RedisProperties redisProperties;

	@Value("${spring.redis.hotwheel.username}")
	private String          redisUserName;

	@Bean
	public <K,V> RedisTemplate<K,V> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory){
		lettuceConnectionFactory.validateConnection();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		RedisTemplate<K, V> template = new RedisTemplate();
		template.setConnectionFactory(lettuceConnectionFactory);
		template.setKeySerializer(new GenericToStringSerializer(Object.class));
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
		template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
		return template;
	}
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐