RPC原理与实例

什么是RPC? RPC是Remote Procedure
Call的缩写,像Client-Servier一样的远程过程调用,也就是调用远程服务就跟调用本地服务一样方便,一般用于将程序部署在不同的机器上,供客户端进行调用。就像一个request-response调用系统一样简单。在面向对象编程的程序中,RPC也可以用Remote
method
invocation(RMI)来展现。为什么用它呢,因为随着分布式结构的普遍,越来越多的应用需要解耦,将不同的独立功能部署发布成不同的服务供调用。
  
**

它的主要流程是Client -> Client Stub -> Network -> Server Stub -> Server

执行完成之后再进行返回。   这里边比较重要的就是Clint Stub和Server
Stub,他们主要的作用就是将调用的方法和参数进行编码(Marshalling)序列化,将序列化后的数据通过网络发送给Server
Stub,然后等待Server回执。Server
Stub将受到的序列化字节进行解码(Unmarshaling)反序列化,然后再将参数传入到对应到的方法中执行,将得出的结果计算出来之后再进行返回,返回的过程和正向的过程类似。

这里写图片描述

###通过RPC原理实现类的远程调用

###client:

public class RpcImporter<S> {
@SuppressWarnings("unchecked")
public S importer(final Class<?> serviceClass,final InetSocketAddress addr){
	return  (S) Proxy.newProxyInstance(
			serviceClass.getClassLoader(),//classloader
			new Class<?>[] {serviceClass.getInterfaces()[0]},//目标类接口 
			//代理类对象
			new InvocationHandler(){
				@Override
				public Object invoke(Object proxy, Method method,
						Object[] args) throws Throwable {
					Socket socket =null;
					ObjectOutputStream output =null;
					ObjectInputStream input=null;		
				try{
					socket=new Socket();
					socket.connect(addr);	
					//client数据序列化输出
					output =new ObjectOutputStream(socket.getOutputStream());
					output.writeUTF(serviceClass.getName());//className
					output.writeUTF(method.getName());//methodname
					output.writeObject(method.getParameterTypes());//param name
					output.writeObject(args);
					//接收数据
					input =new ObjectInputStream(socket.getInputStream());
					return input.readObject();
				}finally{
						if(socket != null)
							socket.close();
						if(output !=null)
							output.close();
						if(input !=null)
							input.close();
				}
		}
	});
}

}

###Service

public class RpcExporter {
//获取cpu核心数
static Executor executor =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//server
public static void exporter(String hostName,int port) throws IOException{
ServerSocket server=new ServerSocket();
server.bind(new InetSocketAddress(hostName,port));
try {
while(true){
executor.execute(new ExporterTask(server.accept()));
}
}finally{
server.close();
}
}
private static class ExporterTask implements Runnable{
Socket client =null;
public ExporterTask(Socket client){
this.client=client;
}
@Override
public void run() {
ObjectInputStream input=null;
ObjectOutputStream output=null;
try {
//反序列化
input =new ObjectInputStream(client.getInputStream());
String interfaceName=input.readUTF();
Class<?> service=Class.forName(interfaceName);
//method name
String methodName=input.readUTF();
//parameter type and argument
Class<?>[] parameterTypes=(Class<?>[])input.readObject();
Object[] arguments=(Object[])input.readObject();
//method
Method method =service.getMethod(methodName, parameterTypes);
//execute method
Object result=method.invoke(service.newInstance(), arguments);
//执行结果,序列化后返回到客户端
output =new ObjectOutputStream(client.getOutputStream());
output.writeObject(result);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(output !=null)
try{
output.close();
}catch(IOException e){
e.printStackTrace();
}
if(input !=null)
try{
input.close();
}catch(IOException e){
e.printStackTrace();
}
if(client !=null)
try{
client.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}


###调用的接口与实现的类:

public interface  EchoService {
String echo(String ping);
String addclient(String clientno);
String deleteclient(String clientno);
String editclient(String clientno);
String selectclient(String clientno);
String pagelist(String clientno);

}
public class EchoServiceImpl implements EchoService{
@Override
public String echo(String ping) {
return ping !=null ? ping + “–> I am ok.” : " I am ko.";
}
@Override
public String addclient(String clientno) {
return clientno !=null ? clientno + “addclient” : “is null”;
}
@Override
public String deleteclient(String clientno) {
// TODO Auto-generated method stub
return clientno !=null ? clientno + “deleteclient.” : " I am ko.";
}
@Override
public String editclient(String clientno) {
// TODO Auto-generated method stub
return clientno !=null ? clientno + “editclient.” : " I am ko.";
}
@Override
public String pagelist(String clientno) {
// TODO Auto-generated method stub
return clientno !=null ? clientno + “pagelist.” : " I am ko.";
}
@Override
public String selectclient(String clientno) {
// TODO Auto-generated method stub
return clientno !=null ? clientno + “selectclient.” : " I am ko.";
}
}

测试:

public class Test {
public static void main(String[] args) throws Exception{
	//服务端
	new Thread (new Runnable(){
		public void run(){
			try{
				RpcExporter.exporter("localhost", 8088);
			}catch(Exception e){
				e.printStackTrace();			
			}
		}
	}).start();
	//客户端
	RpcImporter<EchoService> importer=new RpcImporter<EchoService>();
	//传入类与ip地址,返回代理
	EchoService echo=importer.importer(EchoServiceImpl.class, new InetSocketAddress("localhost",8088));
	
	System.out.println(Runtime.getRuntime().availableProcessors());			
	System.out.println(echo.echo("Are you ok?"));
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值