Java RMI:即Java遠程方法調用,是針對Java語言的一種特殊RPC調用,一種用於實現遠程過程調用的應用程序編程接口。下面用一個簡單實例來說明Java RMI是怎樣開發的。
步驟一:編寫遠程服務接口,該接口必須繼承 java.rmi.Remote 接口,方法必須拋出 java.rmi.RemoteException 異常;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:44:16
*/
public interface IService extends Remote{
String sayHello(String name) throws RemoteException;
}
步驟二:編寫遠程接口實現類,該實現類必須繼承 java.rmi.server.UnicastRemoteObject 類;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:45:19
*/
public class ServiceImpl extends UnicastRemoteObject implements IService{
private static final long serialVersionUID = 1L;
protected ServiceImpl() throws RemoteException {
super();
}
@Override
public String sayHello(String name) throws RemoteException{
System.out.println("Hello " + name);
return "Hello " + name;
}
}
步驟三:啓動一個RMI註冊表,綁定端口。並且把需要對外暴漏的服務註冊進註冊表中
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:47:43
*/
public class Server {
public static void main(String[] args) {
Registry reg = null;
try {
reg = LocateRegistry.createRegistry(8888);
} catch (RemoteException e) {
e.printStackTrace();
}
try {
IService server = new ServiceImpl();
reg.rebind("hello", server);
System.out.println("server bind...");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
服務啓動,這時通過cmd查看端口,已經被監聽:
步驟四:客戶端查找遠程對象,並調用遠程方法
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:51:59
*/
public class Client {
public static void main(String[] args) {
Registry reg = null;
try {
reg = LocateRegistry.getRegistry("127.0.0.1", 8888);
String[] regList = reg.list();
System.out.println("=====服務列表======");
for (String r : regList) {
System.out.println(r);
}
} catch (RemoteException e) {
e.printStackTrace();
}
try {
IService hello = (IService) reg.lookup("hello");
String result = hello.sayHello("stone");
System.out.println("result from remote:"+result);
} catch (RemoteException | NotBoundException e) {
e.printStackTrace();
}
}
}
運行結果如下: