RMI(即Remote Method Invoke 远程方法调用)。在Java中,只要一个类extends了java.rmi.Remote接口,即可成为存在于服务器端的远程对象,供客户端访问并提供一定的服务。JavaDoc描述: Remote 接口用于标识其方法可以从非本地虚拟机上调用的接口。任何远程
1. RMI的原理是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法。可以用此方法调用的任何对象必须实现该远程接口。2. RMI(远程方法调用)的组成 一个正常工作的RMI系统由下面几个部分组成:
远程服务的接口定义
远程服务接口的具体实现
桩(Stub)和框架(Skeleton)文件
一个运行远程服务的服务器
一个RMI命名服务,它允许客户端去发现这个远程服务
类文件的提供者(一个HTTP或者FTP服务器)
一个需要这个远程服务的客户端程序 3. RMI的实现 (1) 编写一个远程接口
import java.rmi.Remote;import java.rmi.RemoteException;public interface HelloService extends Remote { public String sthSays(String sth) throws RemoteException; }(2) 编写远程接口的实现 import java.rmi.RemoteException;import java.rmi.server.UnicastRemoteObject;public class HelloServiceImpl extends UnicastRemoteObject implements HelloService {public HelloServiceImpl() throws RemoteException { super(); } public String sthSays(String sth) throws RemoteException { return sth + " Hello " ;} }(3) 编写服务器端程序 import java.rmi.Naming;import java.rmi.registry.LocateRegistry;public class RmiServer { /** * 启动 RMI 注册服务并进行对象注册 */ public static void main(String[] argv) { try { //启动RMI注册服务,指定Java1.1的“远程方法调用”(RMI)用抽象的概念实现了一台机器调用另外一台机器的方法。简单记录实现方法,以便今后查阅。
RMI对接口有着强烈的依赖。在需要创建一个远程对象的时候,我们通过传递一个接口来隐藏基层的实施细节,所以客户端得到的远程端口为1099(1099为默认端口) //也可以通过命令 $java_home/bin/rmiregistry 1099启动 //而且用命令rmiregistry启动注册服务还必须事先用RMIC生成一个占位程序(stub类)为它所用 LocateRegistry.createRegistry(1099); //创建远程对象的一个或多个实例,下面是hello对象 //可以用不同名字注册不同的实例 HelloService hs = new HelloServiceImpl(); //把hello注册到RMI注册服务器上,命名为Hello Naming.rebind("Hello", hs); //如果要把hello实例注册到另一台启动了RMI注册服务的机器上 //Naming.rebind("//192.168.1.105:1099/Hello",hello); System.out.println("Hello Server is ready."); } catch (Exception e) { System.out.println("Hello Server failed: " + e); } } }(4) 编写客户端程序 import java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException;public class RmiClient { public static void main(String args[]) throws RemoteException, MalformedURLException, NotBoundException {String url="rmi://127.0.0.1/Hello"; HelloService hs; hs = (HelloService)Naming.lookup(url); System.out.println(hs.sthSays("RMI World")); } }