RMI原理
RMI与服务化架构非常相似。server端提供方法调用(服务)并注册到rmiregristry,client端查询rmiregistry并调用方法获得服务。
要实现上述过程,server端需要(1)按照interface实现远程方法;(2) 生成stub;(3)向rmiregristry注册, client端需要(1)按照interface实现远程方法的调用和;(2)获取stub。
RMI实例
1. 客户端和服务端都需要有接口类MyRemote
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
2. 服务端实现服务接口MyRemoteImpl
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
private static final long serialVersionUID = 1L;
public MyRemoteImpl() throws RemoteException{};
public String sayHello() {
return("Server say Hello");
}
public static void main(String [] args) {
try {
MyRemoteImpl service = new MyRemoteImpl();
Naming.rebind("Service_SayHello", service);
} catch (Exception ex) {
System.out.println("MyRemoteImpl - main");
ex.printStackTrace();
}
}
}
3. 客户端实现服务调用MyRemoteClient
import java.rmi.Naming;
public class MyRemoteClient {
public static void main(String [] args) {
new MyRemoteClient().go();
}
void go() {
try {
MyRemote service = (MyRemote) Naming.lookup("rmi://127.0.0.1/Service_SayHello");
String s = service.sayHello();
System.out.println(s);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
4. 生成stub
shell切换到MyRemoteImpl.class所在目录,执行
rmic MyRemoteImpl
生成MyRemoteImpl_Stub.class,发送给客户端。
5. 服务端启动rmiregistry
shell中执行
rmiregistry
6. 服务端运行MyRemoteImpl.java
7. 客户端运行MyRemoteClient.java
如果正常运行,则客户端打印结果“Server say Hello”。
参考资料
本文大部分代码和知识来自于《Head First Java》