1.RMI远程调用:
- Remote Method Invocation
- 目的:把一个接口方法暴露给远程
示例:
定义一个接口Clock,它有一个方法能够获取当前的时间,并编写一个实现类,来实现这个接口。
RMI远程调用示例:
public interface Clock{
//获取当前时间
//LocalDateTime currentTime();
}
public class ClockImpl implements Clock{
public LocalDateTime currentTime() throws RemoteException{
return LocalDateTime.now();
}
}
服务器端:
//创建一个Clock接口的实例
Clock impl = new ClockImpl();
//通过UnicastRemoteObject.exportObject把这个实例和端口暴露到网络上
Clock stub = (Clock) UnicastRemoteObject.exportObject(impl, 1099);
//打开1099的端口
LocalRegistry.createRegistry(1099);
//创建LocalRegistry.getRegistry()创建Registry实例
Registry registry = LocalRegistry.getRegistry();
//将远程调用对象stub绑定到registry,并命名为Clock。这里的名称和客户端查找的名称是一样的
registry.bind("Clock", stub);
客户端:
//获取远程Clock示例:通过registry.lookup(服务名称)获得一个Clock接口的引用
Cllock clock = (Clock) registry.lookup("Clock");
//正常方法调用
LocalDateTime dt = clock.currentTime();

在一个RMI远程调用中,客户端持有的是Clock引用,它只想的真正对象是有JVM帮我们创建的ClockClientStub类,而Server端我们创建的是Clock接口和ClockImpl实现类,JVM同样会创建一个类似于ClockServerStub的包装类型,然后通过网络,简介实现远程调用。
Clock.java
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.time.LocalDateTime;
public interface Clock extends Remote { //远程接口必须继承至Remote接口
LocalDateTime currentTime() throws RemoteException;//每个接口方法也要抛出RemoteException
}
ClockImpl.java
import java.rmi.RemoteException;
import java.time.LocalDateTime;
public class ClockImpl implements Clock{
@Override
public LocalDateTime currentTime() throws RemoteException{
return LocalDateTime.now();
}
}
ClockServer.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class ClockServer {
public static void main(String[] args) throws Exception{
Clock impl = new ClockImpl(); //创建ClockImpl的实例,它是真正用于调用业务的方法
Clock stub = (Clock) UnicastRemoteObject.exportObject(impl,1099);//传入实例、端口,输出为一个stub对象
LocateRegistry.createRegistry(1099); //在1099端口创建一个LocateRegistry对象
Registry registry = LocateRegistry.getRegistry(); //获取这个LocateRegistry对象
registry.bind("Clock",stub); //把stub这个实例绑定到Clock这个名字上
System.out.println("Clock server ready");
}
}

ClockClient.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.time.LocalDateTime;
public class ClockClient {
public static void main(String[] args) throws Exception{
Registry registry = LocateRegistry.getRegistry(); //不传或传入null,代表远程地址是localhost,获得Registry对象
Clock clock = (Clock) registry.lookup("Clock"); //获得远程对象的引用
LocalDateTime dt = clock.currentTime(); //对这个远程对象,正常调用它的方法
System.out.println("RMI result:"+dt);
}
}

2.总结
- RMI远程调用是针对Java语言的一种远程调用
- 远程接口必须继承至Remote
- 远程方法必须抛出RemoteException
- 客户端调用RMI方法和调用本地方法类似
- RMI方法调用被自动通过网络传输到服务器端
- 服务器端通过自动生成的stub类接收远程调用请求。