码迷,mamicode.com
首页 > 编程语言 > 详细

Redis 自定义对象 cannot be cast to java.lang.String

时间:2018-11-17 17:54:35      阅读:668      评论:0      收藏:0      [点我收藏+]

标签:r.java   自定义   span   default   framework   exe   groov   push   .class   

Redis序列化对象的时候报错如下

java.lang.ClassCastException: com.ppdai.cbd.ddp.thirdparty.contract.bhxtzx.BHXTZXTask cannot be cast to java.lang.String
        at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:33)
        at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:117)
        at org.springframework.data.redis.core.DefaultListOperations.leftPush(DefaultListOperations.java:71)
        at org.springframework.data.redis.core.DefaultBoundListOperations.leftPush(DefaultBoundListOperations.java:60)
        at com.ppdai.realtime.datachannel.pullservice.entity.RedisQueue.pushFromHead(RedisQueue.java:63)
        at com.ppdai.realtime.datachannel.pullservice.redisconfig.RedisTaskSender.sendTask(RedisTaskSender.java:35)
        at com.ppdai.realtime.datachannel.pullservice.redisconfig.RedisTaskSender$sendTask.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
BHXTZXTask是自己定义的Bean,因此问题就变成了自定义的对象不能转成String对象,为什么会需要转成String对象呢

查看源码,如下,通过rawValue()函数获取序列化之后的字节码

public Long leftPush(K key, V value) {
        final byte[] rawKey = rawKey(key);
        final byte[] rawValue = rawValue(value);
        return execute(new RedisCallback<Long>() {

            public Long doInRedis(RedisConnection connection) {
                return connection.lPush(rawKey, rawValue);
            }
        }, true);
    }
private byte[] rawValue(Object value) {
if (valueSerializer == null && value instanceof byte[]) {
return (byte[]) value;
}
return valueSerializer.serialize(value);
}
 

通过 valueSerializer序列化来序列化对象, redis如果不配置,默认 valueSerializer的序列化是会使用

StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();

        System.out.println(redisTemplate.hasKey("bohai_credit"));
        redisTemplate.delete("bohai_credit");

        System.out.println(stringRedisSerializer.serialize("bohai_credit"));
        System.out.println(jdkSerializationRedisSerializer.serialize("bohai_credit"));
[B@21831984
[B@4488db1f

运行结果如上所示。

Redis 自定义对象 cannot be cast to java.lang.String

标签:r.java   自定义   span   default   framework   exe   groov   push   .class   

原文地址:https://www.cnblogs.com/zhengwangzw/p/9965406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!