开发步骤:
1.写接口,继承java.rmi.Remote
2.写该接口的实现类,并注册,注册代码
LocateRegistry.createRegistry(1099);
Naming.rebind(“rmi://:1099/registryName”, serverName);
3.客户端调用
客户端写接口,并调用,调用代码
Server server = (Server) Naming.lookup(“rmi://127.0.0.1:1099/registryName”);
示例如下:
package app;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Server extends Remote {
String helloWorld()throws RemoteException;
}
package app;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Server1 extends Remote{
String getMes()throws RemoteException;
}
package app;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server1Iml extends UnicastRemoteObject implements Server1 {
protected Server1Iml() throws RemoteException {
}
public String getMes() throws RemoteException {
return "成功调用server1";
}
}
package app;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class ServerIml extends UnicastRemoteObject implements Server {
protected ServerIml() throws RemoteException {
}
public String helloWorld() throws RemoteException {
return "hello world";
}
public static void main(String[] args) throws Exception{
Server server = new ServerIml();
LocateRegistry.createRegistry(1099);
Naming.rebind("rmi://:1099/crazyit", server);
Server1 server1 = new Server1Iml();
Naming.rebind("rmi://:1099/server1", server1);
}
}
package app;
import java.rmi.Naming;
public class RMIClient {
public static void main(String[] args) throws Exception{
Server server = (Server) Naming.lookup("rmi://127.0.0.1:1099/crazyit");
String ms = server.helloWorld();
System.out.println(ms);
Server1 server1 = (Server1) Naming.lookup("rmi://127.0.0.1:1099/server1");
String mes = server1.getMes();
System.out.println(mes);
}
}
先启动服务端,再启动客户端,控制台打印如下:
hello world
成功调用server1
原理与应用:
1.RMI是对socket的封装,省去了socket通信和多线程的管理
2.对于大型分布式系统,我们要使用远程的方法,只要把远程的方法注册下即可通过RMI进行调用,当然,当前restful框架很多,我们也可以用通过对RMI封装写出自己的库