用dubbo時遇到的一個序列化的坑

  首先,這是標題黨,問題並非出如今序列化上,這是報錯的一部分:java

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):git

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...,固然上面的精簡代碼是能一眼猜到問題在哪,不過本來的代碼好幾百行,查的這個費勁,其實看到這個精簡代碼你們也基本能夠猜到問題在哪了:github

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;
    }
}

結果就正常了:網絡

==========================================================this

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

微信公衆號:code

 

 

轉載請註明出處blog

相關文章
相關標籤/搜索