1.序列化和反序列化
网络中都是以字节序列的形式来传输数据的,因此在发送消息时需要先将对象序列化转换为字节序列,然后将获得的字节序列发送出去,消息接收方接收到字节序列后将之反序列化获得传输的对象,从收发双方来看就如同直接发送和接收了对象一样。
2.第三方依赖
本例使用目前最新版的kryo-serializers 0.36用于序列化
<dependency>
<groupId>de.javakaffee</groupId>
<artifactId>kryo-serializers</artifactId>
<version>0.36</version>
</dependency>
使用maven直接在pom.xml中添加上面的依赖即可
3.序列化和反序列化的实现
序列化和反序列化的对象在本例中只有两种:1.客户端向服务端发出的调用请求RpcRequest 2.服务端向客户端返回的调用结果RpcResponse
(1).RpcResponse
从RPC服务端传回给客户端的某次调用请求的结果
package com.maigo.rpc.context;
public class RpcResponse
{
private int id;
private Object result;
private Throwable throwable;
private boolean isInvokeSuccess;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public Object getResult()
{
return result;
}
public void setResult(Object result)
{
this.result = result;
}
public Throwable getThrowable()
{
return throwable;
}
public void setThrowable(Throwable throwable)
{
this.throwable = throwable;
}
public boolean isInvokeSuccess()
{
return isInvokeSuccess;
}
public void setInvokeSuccess(boolean isInvokeSuccess)
{
this.isInvokeSuccess = isInvokeSuccess;
}
}
RpcResponse中的id对应着该次请求的RpcRequest中的id,isInvokeSuccess表示调用中是否有异常抛出,result和throwable分别表示调用结果和调用过程抛出的异常。
(2).RpcRequest
已在上一节中给出