Rmi远程调用机制

来源:互联网 发布:数据挖掘 面试 编辑:程序博客网 时间:2024/06/05 19:07

       RMI是Java的一组拥护开发分布式应用程序API。RMI使用Java语言接口定义了远程对象,它集合了Java序列化和Java远程方法协议(Java Remote Method Protocol)。简单地说,这样使原先的程序在同一操作系统的方法调用,变成了不同操作系统之间程序的方法调用,由于J2EE是分布式程序平台,它以RMI机制实现程序组件在不同操作系统之间的通信。比如,一个EJB可以通过RMI调用Web上另一台机器上的EJB远程方法。

下图为rmi的结构调用示意:

      

下面给出一个简单的RMI 应用,其中类图如下:其中IService接口用于声明服务器端必须提供的服务(即service()方法),ServiceImpl类是具体的服务实现类,而Server类是最终负责注册服务器远程对象,以便在服务器端存在骨架代理对象来对客户端的请求提供处理和响应。


各个类源码实现为:

IService:

package com.base;import java.rmi.Remote;import java.rmi.RemoteException;/** *@author wanghjbuf *@date 2017年4月21日下午5:02:48 *@version 1.0 *@parameter */public interface IService extends Remote{public String service(String content) throws RemoteException;}

IServiceImpl:

package com.base;import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;/** *@author wanghjbuf *@date 2017年4月21日下午5:04:22 *@version 1.0 *@parameter */@SuppressWarnings("serial")public class IServiceImpl extends UnicastRemoteObject implements IService{@SuppressWarnings("unused")private String name;public IServiceImpl(String name) throws RemoteException{ this.name=name;}@Overridepublic String service(String content){return ">>>>:"+content;}}

Server:

package com.server;import java.rmi.registry.LocateRegistry;import javax.naming.Context;import javax.naming.InitialContext;import com.base.IService;import com.base.IServiceImpl;/** *@author wanghjbuf *@date 2017年4月21日下午5:10:55 *@version 1.0 *@parameter */public class Server {public static void main(String[] args) {try{IService server = new IServiceImpl("server");LocateRegistry.createRegistry(8888);Context namingContext = new InitialContext();namingContext.rebind("rmi://192.168.188.112:8888/server", server);}catch(Exception e){e.printStackTrace();}System.out.println("服务器注册一个远程服务器!");}}

Client:

package com.client;import javax.naming.Context;import javax.naming.InitialContext;import com.base.IService;/** *@author wanghjbuf *@date 2017年4月21日下午5:15:15 *@version 1.0 *@parameter */public class Client {@SuppressWarnings("rawtypes")public static void main(String[] args) {String url = "rmi://192.168.188.112:8888/";try{Context namingContext = new InitialContext();IService client = (IService)namingContext.lookup(url+"server");    Class clientClass = client.getClass();    System.out.println("server:"+clientClass.getName());        Class[] interfaces = clientClass.getInterfaces();    for(Class c : interfaces){    System.out.println("interface:"+c.getName());    }        System.out.println(client.service("hello!"));}catch(Exception e){e.printStackTrace();}}}

输出结果如下:

服务端:


客户端:




1 0
原创粉丝点击