I faced the ClassCastException exception when using the StringRedisSerializer to store hash value. if if remove the non-string field 'age', then it can be stored into redis.
Demo demo = new Demo();
demo.setName("DemoCache_jsonSerializer");
// non-string field
demo.setAge(111);
// set stringSerializer
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
//exception here: java.lang.Integer cannot be cast to java.lang.String
redisTemplate.opsForHash().putAll("testKey",
mapper.toHash(demo));
I know if I change to jsonserializer it will work, but my question is how to keep it work with the StringRedisSerializer ,and able to store object that has non-string fields
2 Answers 2
Using StringRedisSerializer you can only convert String to byte[] and byte[] to String.
To keep it working with StringRedisSerializer better convert all the object to String maybe override toString(). But I guess this might be a bad design.
Have a look at the below links : Source Code and Documentation you might find something helpful.
1 Comment
@Bean
public RedisTemplate<String, Object> redisTemplate() {
final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
template.afterPropertiesSet();
return template; }