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
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.