RPC框架之RMI

Posted on 2019-03-04 21:41  FLGB  阅读(394)  评论(0编辑  收藏  举报

 一:RPC 远程过程调用

 RPC(Remote Procedure Call Protocol)远程过程调用协议,通过网络从远程计算机上请求调用某种服务。

 一次RPC调用的过程大概有10步:

  1.执行客户端调用语句,传送参数

  2.调用本地系统发送网络消息

  3.消息传送到远程主机

  4.服务器得到消息并取得参数 

  5.根据调用请求以及参数执行远程过程(服务)

  6.执行过程完毕,将结果返回服务器句柄

  7.服务器句柄返回结果,调用远程主机的系统网络服务发送结果

  8.消息传回本地主机 

  9.客户端句柄由本地主机的网络服务接收消息

  10.客户端接收到调用语句返回的结果数据

 

 二:RMI 远程方法调用

 RMI:远程方法调用(Remote Method Invocation)。能够让在客户端Java虚拟机上的对象像调用本地对象一样调用服务端java 虚拟机中的对象上的方法。

RMI远程调用步骤:

1,客户调用客户端辅助对象stub上的方法

2,客户端辅助对象stub打包调用信息(变量,方法名),通过网络发送给服务端辅助对象skeleton

3,服务端辅助对象skeleton将客户端辅助对象发送来的信息解包,找出真正被调用的方法以及该方法所在对象

4,调用真正服务对象上的真正方法,并将结果返回给服务端辅助对象skeleton

5,服务端辅助对象将结果打包,发送给客户端辅助对象stub

6,客户端辅助对象将返回值解包,返回给调用者

7,客户获得返回值

 

 三:RPC与RMI的区别

 1:方法调用方式不同:

 RMI中是通过在客户端的Stub对象作为远程接口进行远程方法的调用每个远程方法都具有方法签名。如果一个方法在服务器上执行,但是没有相匹配的签名被添加到这个远程接口(stub)上,那么这个新方法就不能被RMI客户方所调用

 

  RPC中是通过网络服务协议向远程主机发送请求,请求包含了一个参数集和一个文本值,通常形成“classname.methodname(参数集)”的形式。RPC远程主机就去搜索与之相匹配的类和方法,找到后就执行方法并把结果编码,通过网络协议发回。

 

  2:适用语言范围不同:

   RMI只用于Java;

   RPC是网络服务协议,与操作系统和语言无关。

 

  3:调用结果的返回形式不同:

    Java是面向对象的,所以RMI的调用结果可以是对象类型或者基本数据类型;

    RMI的结果统一由外部数据表示 (External Data Representation, XDR) 语言表示,这种语言抽象了字节序类和数据类型结构之间的差异。以上转载地址:http://www.cnblogs.com/ygj0930/p/6542811.html

 

其他的RPC框架:RMI(JRMP)、soap(webservice、axis、cxf)、thrift\grpc\dubbo等

RMI简单demo

1.创建服务类  

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IHelloService extends Remote{
	
	public String sayHello(String msg) throws RemoteException;//需要抛此异常
}
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloServiceImpl extends UnicastRemoteObject implements IHelloService{

	protected HelloServiceImpl() throws RemoteException {
		super();
	}

	@Override
	public String sayHello(String msg) throws RemoteException{
		// TODO Auto-generated method stub
		return "hello"+msg;
	}
	
}

2.发布、注册服务

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class Server {
    
    public static void main(String[] args) {
        try {
            IHelloService helloService = new HelloServiceImpl();//已经发发了一个远程对象
            LocateRegistry.createRegistry(1099);
            try {
                //注册中心key-value
                Naming.rebind("rmi://127.0.0.1/hello", helloService);
                System.out.println("服务启动成功!");
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

3.服务的调用

import com.lf.rmi.HelloServiceImpl;
import com.lf.rmi.IHelloService;

public class ClientDemo {
    
    public static void main(String[] args) {
        
//        IHelloService helloService = new HelloServiceImpl();
//        String msg = helloService.sayHello(" zhangsan");
//        System.out.println(msg);
        
        try {
            //从注册中心拿到代理对象   HelloServiceImpl_stub代理对象
            IHelloService helloService=(IHelloService) Naming.lookup("rmi://127.0.0.1/hello");
            String sayHello = helloService.sayHello(" zhangsan");
            System.out.println(sayHello);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NotBoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

 

 源码分析:

 

一定要说明,在 RMI Client 实施正式的 RMI 调用前,它必
须通过 LocateRegistry 或者 Naming 方式到 RMI 注册表寻
找要调用的 RMI 注册信息。找到 RMI 事务注册信息后,
Client 会从 RMI 注册表获取这个 RMI Remote Service 的
Stub 信息。这个过程成功后,RMI Client 才能开始正式的
调用过程。
另外要说明的是 RMI Client 正式调用过程,也不是由 RMI
Client 直接访问 Remote Service,而是由客户端获取的
Stub 作为 RMI Client 的代理访问 Remote Service 的代理
Skeleton,如上图所示的顺序。也就是说真实的请求调用是
在 Stub-Skeleton 之间进行的。
Registry 并不参与具体的 Stub-Skeleton 的调用过程,只
负责记录“哪个服务名”使用哪一个 Stub,并在 Remote
Client 询问它时将这个 Stub 拿给 Client(如果没有就会报
错)。


手动实现简易 RPC 框架

server端

创建接口类
package rpc;

public interface IHelloWorld {
	
	public String sayHello(String msg);
}

  

创建实现类
package rpc;

public class HelloWorldServiceImpl implements IHelloWorld {

	@Override
	public String sayHello(String msg) {
		// TODO Auto-generated method stub
		return "HelloWorld,"+msg;
	}

}

  

创建服务类
package rpc;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcServer {
	
	private static final ExecutorService  executorService = Executors.newCachedThreadPool();
	public void publisher(final Object service,int port){
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(port);//启动一个服务监听
			while(true){
				Socket socket = serverSocket.accept();
				executorService.execute(new ProcessorHandler(socket,service));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(serverSocket!=null){
				try {
					serverSocket.close();
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}

  

创建传输类
package rpc;

import java.io.Serializable;
/**
 * 传输对象
 * @author admin
 *
 */
public class RpcRequest implements Serializable{
    
    private static final long serialVersionUID = 6351477854838485391L;
    private String className;
    private String methodName;
    private Object[] parameters;
    public RpcRequest(String className, String methodName, Object[] parameters) {
        super();
        this.className = className;
        this.methodName = methodName;
        this.parameters = parameters;
    }
    
    public RpcRequest() {
        super();
        // TODO Auto-generated constructor stub
    }

    public String getClassName() {
        return className;
    }
    public void setClassName(String className) {
        this.className = className;
    }
    public String getMethodName() {
        return methodName;
    }
    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
    public Object[] getParameters() {
        return parameters;
    }
    public void setParameters(Object[] parameters) {
        this.parameters = parameters;
    }
    
}
创建服务处理handler
package rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

public class ProcessorHandler implements Runnable {
	
	private Socket socket;
	private Object service;//服务端发布的服务
	
	
	public ProcessorHandler(Socket socket, Object service) {
		this.socket = socket;
		this.service = service;
	}


	@Override
	public void run() {
		// TODO 处理请求
		ObjectInputStream objectInputStream =null;
		ObjectOutputStream objectOutputStream =null;
		try {
			objectInputStream = new ObjectInputStream(socket.getInputStream());
			RpcRequest request = (RpcRequest) objectInputStream.readObject();
			Object result = invoke(request);
			objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectOutputStream.writeObject(result);
			objectOutputStream.flush();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(objectInputStream!=null){
				try {
					objectInputStream.close();
					objectOutputStream.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private Object invoke(RpcRequest request) throws Exception, IllegalArgumentException, InvocationTargetException{
		Object[] args = request.getParameters();
		Class<?> [] types = new Class[args.length];
		for (int i = 0; i < types.length; i++) {
			types[i] = args[i].getClass();
		}
		Method method = service.getClass().getMethod(request.getMethodName(), types);
		return method.invoke(service, args);
	}
}

  

创建服务发布类
package rpc;

public class ServerDemo {
	
	public static void main(String[] args) {
		IHelloWorld service = new HelloWorldServiceImpl();
		RpcServer server  = new RpcServer();
		System.out.println("服务已发布!");
		server.publisher(service, 8888);
		
	}
}

  

client端

创建接口和传输类,注意包路径和服务方一致(或将接口和传输类变成jar,导入客户端)
package rpc;

public interface IHelloWorld {
	
	public String sayHello(String msg);
}
package rpc;

import java.io.Serializable;
/**
 * 传输对象
 * @author admin
 *
 */
public class RpcRequest implements Serializable{
	
	private static final long serialVersionUID = 6351477854838485391L;
	private String className;
	private String methodName;
	private Object[] parameters;
	public RpcRequest(String className, String methodName, Object[] parameters) {
		super();
		this.className = className;
		this.methodName = methodName;
		this.parameters = parameters;
	}
	
	public RpcRequest() {
		super();
		// TODO Auto-generated constructor stub
	}

	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getMethodName() {
		return methodName;
	}
	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}
	public Object[] getParameters() {
		return parameters;
	}
	public void setParameters(Object[] parameters) {
		this.parameters = parameters;
	}
	
}

  

创建代理类
package rpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RpcClientProxy {
	
	public <T> T clientProxy(final Class<T> interfaceCls,final String host,final int port){
		
		return (T) Proxy.newProxyInstance(interfaceCls.getClassLoader(),
				new Class[] {interfaceCls},
                 new RemoteInvocationHandler(host,port));
		
	} 
}

  

创建客户端handler
package rpc;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;



public class RemoteInvocationHandler implements InvocationHandler {
	
	private String host;
	private int port;
	
	public RemoteInvocationHandler(String host, int port) {
		this.host = host;
		this.port = port;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// TODO Auto-generated method stub
		RpcRequest request = new RpcRequest();
		request.setClassName(method.getDeclaringClass().getName());
		request.setMethodName(method.getName());
		request.setParameters(args);
		
		TcpTransport trans = new TcpTransport(host, port);
		return trans.send(request);
	}

}

  

创建连接传输类
package rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;


public class TcpTransport {
	
	private String host;
	private int port;
	
	public TcpTransport(String host, int port) {
		super();
		this.host = host;
		this.port = port;
	}
	
	Socket newSocket(){
		System.out.println("创建一个连接");
		Socket socket = null;
		try {
			socket = new Socket(host,port);
			return socket;
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException("连接建立失败!");
		}
	}
	
	public Object send(RpcRequest request){
		Socket socket = null;
		ObjectOutputStream objectOutputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			socket = newSocket();
			
			objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectOutputStream.writeObject(request);
			objectOutputStream.flush();
			
			objectInputStream = new ObjectInputStream(socket.getInputStream());
			Object readObject = objectInputStream.readObject();
			return readObject;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new RuntimeException("连接建立失败!");
		}finally {
			if(socket!=null){
				try {
					socket.close();
					objectOutputStream.close();
					objectInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}

  

发起客户端调用
package rpc;


public class ClientDemo {
	public static void main(String[] args) {
		RpcClientProxy rpcClientProxy = new RpcClientProxy();
		IHelloWorld hello = rpcClientProxy.clientProxy(IHelloWorld.class, "localhost", 8888);
		System.out.println(hello.sayHello("lf"));
	}
}

  

 

Copyright © 2024 FLGB
Powered by .NET 9.0 on Kubernetes