I just knew that enabling USE_LONG_FOR_INTS
can convert Integer to Long, and then I set my redisTemplate like that:
@Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(DeserializationFeature.USE_LONG_FOR_INTS); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); template.setKeySerializer(RedisSerializer.string()); template.setHashKeySerializer(RedisSerializer.string()); template.setDefaultSerializer(jackson2JsonRedisSerializer); return template; }
But it didn't work as expected when I set a key-value in redis:
@Test void test() throws JsonProcessingException { redisTemplate.opsForValue().set("key", 11); System.out.println(redisTemplate.opsForValue().get("key").getClass()); }
This will print Integer instead of Long.
I spend lots of time going through the source code and I kinda get it because the deserialization finally will get into the function com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer.Vanilla#deserializeWithType
, which won't check if you enabled the feature USE_LONG_FOR_INTS
, but only this feature USE_BIG_INTEGER_FOR_INTS
.
I wonder how to let it return a Long value, or it just has no solution to it.