1.RPC服务端的实现思路
相对于客户端而言,服务端要简单不少。基本思想就是,创建RPC服务端的时候,创建一个RPC请求队列和一定数量的Handler线程。Handler线程都持有服务端提供服务的Interface的类类型和实际供方法调用的对象(实现了提供服务的Interface),各线程只需要不断从RPC请求队列中取出请求,然后用供方法调用的对象来调用所请求的方法,最后将调用的结果通过Netty发送回客户端即可。
2.RPC服务端的具体实现
(1).RpcRequest
在具体实现RPC服务端之前,先定义RpcRequest类。
package com.maigo.rpc.context;
public class RpcRequest
{
int id;
String methodName;
Object[] args;
public RpcRequest(int id, String methodName, Object[] args)
{
this.id = id;
this.methodName = methodName;
this.args = args;
}
public int getId()
{
return id;
}
public String getMethodName()
{
return methodName;
}
public Object[] getArgs()
{
return args;
}
}
RpcRequest表示了一个RPC调用请求。id用于区分多次不同的调用,methodName为请求调用的方法名,args为参数。
(2).RpcServerBuilder
RpcServerBuilder是创建RpcServer的工厂类
package com.maigo.rpc.server;
import com.maigo.rpc.aop.RpcInvokeHook;
public class RpcServerBuilder
{
private Class<?> interfaceClass;
private Object serviceProvider;
private int port;
private int threads;
private RpcInvokeHook rpcInvokeHook;
public static RpcServerBuilder create()
{
return new RpcServerBuilder();
}
/**
* set the interface to provide service
* @param interfaceClass
*/
public RpcServerBuilder serviceInterface(Class<?> interfaceClass)
{
this.interfaceClass = interfaceClass;
return this;
}
/**
* set the real object to provide service
*/
public RpcServerBuilder serviceProvider(Object serviceProvider)
{
this.serviceProvider = serviceProvider;
return this;
}
/**
* set the port to bind
*/
public RpcServerBuilder bind(int port)
{
this.port = port;
return this;
}
/**
* set the count of threads to handle request from client. (default availableProcessors)
*/
public RpcServerBuilder threads(int threadCount)
{
this.threads = threadCount;
return this;
}
/**
* set the hook of the method invoke in server
*/
public RpcServerBuilder hook(RpcI