I'm using RedisTemplate to store Long
value, I store it successfully, I expect that I can get that Long
value back, but the type of that value is not Long
, but Integer
.
RedisTemplate<String, Object> = redisTemplate();
Long l = 1L;
redisTemplate.opsForValue().set("l", l);
Object o = redisTemplate.opsForValue().get("l");
System.out.println(o.getClass().getName()); // the output is "java.lang.Integer", not "java.lang.Long"
public RedisTemplate<String, Object> redisTemplate() {
// setup jackson2JsonRedisSerializer
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
// https://stackoverflow.com/questions/7105745/how-to-specify-jackson-to-only-use-fields-preferably-globally
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
// https://stackoverflow.com/questions/17694042/jackson-default-typing-for-object-containing-a-field-of-mapstring-object
.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
JedisConnectionFactory jedisConnectionFactory = createFactory(); // you don't need to worry about `createFactory()`
redisTemplate.setConnectionFactory(jedisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
How can I preserve type info when using RedisTemplate
to store data?