如何使用java RMI 包实现一个RPC
1.需要使用到的两个类:
java.rmi.server.UnicastRemoteObject类和java.rmi.Remote接口
1.Remote接口
源代码:
/**
* The <code>Remote</code> interface serves to identify interfaces whose
* methods may be invoked from a non-local virtual machine.
* */
public interface Remote {}
Remote 接口用来确定一些接口,这些接口的方法将被远端虚拟机调用。
在远端客户端和本地的服务之间需要定义一个接口,这个接口将被作为通用接口来提供客户端使用。而这个通用的接口需要继承于Remote接口。
public interface RMIQueryStatus extends Remote {
String getStatus() throws RemoteException;
}
2.UnicastRemoteObject类
源代码:
/**
* Used for exporting a remote object with JRMP and obtaining a stub
* that communicates to the remote object.
**/
public class UnicastRemoteObject extends RemoteServer {
}
UnicastRemoteObject类用来提供一个带有java远程方法协议的对象,并且还保留一个与远端对象交流的存根。
源代码:
protected UnicastRemoteObject(int port) throws RemoteException
{
this.port = port;
exportObject((Remote) this, port);
}
UnicastRemoteObject对象就是最终需要new的对象,它需要继承与Remote接口,并且new了这个对象后,会有一个后台的进程。远端的客户端调用的也是这个对象的方法。
public class RMIQueryStatusImpl extends UnicastRemoteObject implements RMIQueryStatus {
protected RMIQueryStatusImpl() throws RemoteException {
super();
}
@Override
public String getStatus() throws RemoteException {
return "yes";
}
}
2.本地服务端代码和远端客户端代码
服务端:
public class RpcServer {
public static final String RMI_URI = "rmi://10.12.40.60:16290/query";
public static void main(String[] args) {
try {
RMIQueryStatusImpl queryservice = new RMIQueryStatusImpl();
LocateRegistry.createRegistry(16290);
Naming.rebind(RMI_URI, queryservice);
System.out.println("Server ready!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端:
public class RpcClient {
public static final String RMI_URI = "rmi://10.12.40.60:16290/query";
public static void main(String[] args) {
try {
RMIQueryStatus query = (RMIQueryStatus) Naming.lookup(RMI_URI);
String s = query.getStatus();
System.out.println("Client get value: " + s);
} catch (Exception e) {
e.printStackTrace();
}
}
}