• 用dubbo时遇到的一个序列化的坑


      首先,这是标题党,问题并不是出现在序列化上,这是报错的一部分:

    Caused by: com.alibaba.dubbo.remoting.RemotingException: Failed to send response: Response [id=24, version=2.0.0, status=20, event=false, error=null, result=RpcResult [result=xxxService$7@57e8ec64, exception=null]], cause: java.lang.RuntimeException: Serialized class xxxService must implement java.io.Serializable
     Java field: final xxxService xxxService$7.this$0
    java.lang.RuntimeException: Serialized class xxxService must implement java.io.Serializable
     Java field: final xxxService xxxService$7.this$0
        at com.alibaba.com.caucho.hessian.io.JavaSerializer$FieldSerializer.serialize(JavaSerializer.java:315)
        at com.alibaba.com.caucho.hessian.io.JavaSerializer.writeInstance(JavaSerializer.java:263)
        at com.alibaba.com.caucho.hessian.io.JavaSerializer.writeObject(JavaSerializer.java:227)
        at com.alibaba.com.caucho.hessian.io.Hessian2Output.writeObject(Hessian2Output.java:408)
        at com.alibaba.dubbo.common.serialize.support.hessian.Hessian2ObjectOutput.writeObject(Hessian2ObjectOutput.java:92)
        at com.alibaba.dubbo.rpc.protocol.dubbo.DubboCodec.encodeResponseData(DubboCodec.java:210)

      报了错的是注册给dubbo的service端,代码类似这样(https://github.com/saaavsaaa/warn-report/blob/master/src/test/java/TestObjectInstance.java):

    class SService{
        public A getA(){
            A a = new A(){{setN("dto");}};
            return a;
        }
    }
    
    class A{
        protected String n;
    
        public A(){
            n = "a";
        }
    
        public String getN() {
            return n;
        }
    
        public void setN(String n) {
            this.n = n;
        }
    }
        @Test
        public void testSerializ(){
            SService s = new SService();
            A a = s.getA();
            System.out.println(a.getN());
        }

       这什么情况,虽然通过dubbo的网络传输是需要序列化的,但是你要我把sevice也实现Serializable是闹哪样,然后紧接着发现了个更奇怪的事:第二行Java field: final xxxService xxxService$7.this$0,哪来的field,哪也没定义过这玩意,怎么还有个this...,当然上面的精简代码是能一眼猜到问题在哪,不过原本的代码好几百行,查的这个费劲,其实看到这个精简代码大家也基本可以猜到问题在哪了:

    A a = new A(){{setN("dto");}};

    代码改成:

    class SService{
        public A getA(){
    //        A a = new A(){{setN("dto");}};
            A a = new A();
            a.setN("dto");
            return a;
        }
    }

    结果就正常了:

    ==========================================================

    咱最近用的github:https://github.com/saaavsaaa

    微信公众号:

     

    转载请注明出处

  • 相关阅读:
    09 Django组件之用户认证组件
    二叉树的三种遍历(非递归)
    CoderForce 141C-Queue (贪心+构造)
    CoderForce 140C-New Year Snowmen(贪心)
    UVA-1663 Purifying Machine (最大匹配数)
    UVA-10801 Lift Hopping (最短路)
    UVA-1660 Cable TV Network (最小割)
    UVA-820 Internet Bandwidth (最大流)
    UVA-1336 Fixing the Great Wall(区间DP)
    棋盘分割(二维区间DP)
  • 原文地址:https://www.cnblogs.com/saaav/p/6095305.html
Copyright © 2020-2023  润新知