I've got this exception.
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
2025-03-27 17:19:16 at com.example.ordermicroservice.service.RedisService.getBalance(RedisService.kt:45) ~[!/:0.0.1-SNAPSHOT]
2025-03-27 17:19:16 at com.example.ordermicroservice.service.AccountService$deposit$2$1.invokeSuspend(AccountService.kt:59) ~[!/:0.0.1-SNAPSHOT]
2025-03-27 17:19:16 at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) ~[kotlin-stdlib-1.9.25.jar!/:1.9.25-release-852]
With this code.
fun getBalance(accountNumber: String): Long {
return numericRedisTemplate.opsForValue().get(accountNumber) ?: -1L
}
and my spring boot redis configuration.
@Bean
fun numericRedisTemplate(redisConnectionFactory: LettuceConnectionFactory): RedisTemplate<String, Long> {
val template = RedisTemplate<String, Long>()
template.connectionFactory = redisConnectionFactory
template.keySerializer = StringRedisSerializer(Charsets.UTF_8)
template.valueSerializer = GenericJackson2JsonRedisSerializer()
template.hashKeySerializer = StringRedisSerializer(Charsets.UTF_8)
template.hashValueSerializer = GenericJackson2JsonRedisSerializer()
return template
}
I request value of Long type but there's ClassCastException
. So does Redis save Long as Int?
numericRedisTemplate
has an incorrect value serializer for its value type.
The value type is Long
, but the serializer is for json.
So remove these lines from the numericRedisTemplate
bean definition:
template.valueSerializer = GenericJackson2JsonRedisSerializer()
template.hashValueSerializer = GenericJackson2JsonRedisSerializer()
Or replace them by these
template.hashValueSerializer = GenericToStringSerializer(Long::class.java)
template.valueSerializer = GenericToStringSerializer(Long::class.java)