2

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

asked Sep 15, 2017 at 6:43

2 Answers 2

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.

answered Sep 15, 2017 at 9:02
Sign up to request clarification or add additional context in comments.

1 Comment

@MunimMunna, I somehow missed this. Thanks for pointing out. Will be careful next time.
1
 @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; }
answered May 15, 2019 at 8:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.