• 用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

    微信公众号:

     

    转载请注明出处

  • 相关阅读:
    JVM探究之 —— HotSpot虚拟机对象探秘
    JVM探究之 —— Java内存区域
    线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式
    dubbo线程模型配置
    hash bucket
    java 查看线程的信息
    List,Set,Map存取元素各有什么特点
    java 让图片变黑白
    springMVC 防重校验(拦截器)
    BigDecimal 的幂次方运算
  • 原文地址:https://www.cnblogs.com/saaav/p/6095305.html
Copyright © 2020-2023  润新知