一、RPC远程调用过程分析
---------------------------------------------
1.定义协议(接口)
//这个接口是所有RPC的父接口
public interface VersionedProtocol {
public long getProtocolVersion(String protocol,
long clientVersion) throws IOException;
public ProtocolSignature getProtocolSignature(String protocol,
long clientVersion,
int clientMethodsHash) throws IOException;
}
}
/**
* 定制协议接口
*/
public interface IHelloWordService extends VersionedProtocol{
public static final long versionID = 1l;
public String sayHello(String mag);
}
2.创建接口的实现类
/**
* 自定义实现接口
* @author Administrator
*
*/
public class HelloWorldServerImpl implements IHelloWordService {
/**
* 返回协议的版本号
*/
public long getProtocolVersion(String protocol, long clientVersion) throws IOException {
return versionID;
}
/**
* 返回协议的签名
*/
public ProtocolSignature getProtocolSignature(String protocol, long clientVersion, int clientMethodsHash)
throws IOException {
return new ProtocolSignature(versionID,null);
}
/**
* 业务方法
*/
public String sayHello(String msg) {
System.out.println(msg);
return "hello" + msg;
}
}
3.创建服务端
/**
* 创建服务器端
* @author Administrator
*
*/
public class MyServer {
public static void main(String[] args) throws Exception {
//配置server
Builder builder = new RPC.Builder(new Configuration());
builder.setProtocol(IHelloWordService.class);
builder.setInstance(new HelloWorldServerImpl());
builder.setBindAddress("localhost");
builder.setPort(7777);
builder.setnumReaders(2); //处理器个数
//开始构建Server
Server ser = builder.build();
//启动server
ser.start();
}
}
4.创建客户端
/**
* 创建客户端
* @author Administrator
*
*/
public class MyClient {
public static void main(String[] args) throws Exception {
//设定配置文件
Configuration conf = new Configuration();
//开启远程代理对象,进行方法的代理
IHelloWordService proxy = RPC.getProxy(IHelloWordService.class,
IHelloWordService.versionID, new InetSocketAddress("localhost", 7777), conf);
//执行代理方法
String result = proxy.sayHello("tom cat");
//打印代理方法的结果
System.out.println(result);
}
}
5.运行
a.运行服务端
b.运行客户端