@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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐