远程方法调用是计算机与计算机之间通过远程对象的相互调用,从而实现双方通讯的一种编程实现机制。通过这种机制,一台计算机的对象可以调用远程另外一台计算机上的对象来获取数据。
远程调用的类是需要序列化的,实现java接口Serializable,便具备序列化条件,java序列化查看 点击打开链接
一、代码实现
model类:
public class SerializableContainer implements Serializable{
private static final long serialVersionUID = 6589196133289807424L;
private String id;
private String name;
private String version;
private Date time;
public SerializableContainer(){}
public SerializableContainer(String id, String name, String version, Date time){
this.id = id;
this.name = name;
this.version = version;
this.time = time;
}
//get,set method of attributes ...
}
远程调用接口:
public interface ContainerRemoteWave extends Remote{
public List<SerializableContainer> containers() throws RemoteException;
}
远程调用接口实现类:
public class ContainerRemoteService extends UnicastRemoteObject implements ContainerRemoteWave{
private static final long serialVersionUID = -3364427307179485046L;
protected ContainerRemoteService() throws RemoteException {
super();
}
@Override
public List<SerializableContainer> containers() throws RemoteException {
List<SerializableContainer> cts = new ArrayList<SerializableContainer>();
cts.add(new SerializableContainer("first", "LAM1", "0.01", new Date(System.currentTimeMillis())));
cts.add(new SerializableContainer("second", "LAM2", "0.02", new Date(System.currentTimeMillis())));
cts.add(new SerializableContainer("third", "LAM3", "0.03", new Date(System.currentTimeMillis())));
return cts;
}
}
远程调用服务端:
public class RemoteServer {
public static void main(String[] args) {
try {
String name = "ContainerRemoteService";
ContainerRemoteWave containerRemote = new ContainerRemoteService();
//注册通讯端口
Registry registry = LocateRegistry.createRegistry(4567);
//注册通讯路径
registry.bind(name, containerRemote);
System.out.println("Remote Server Start.");
//回车,程序退出。
System.in.read();
System.out.println("Remote Server Stop.");
registry.unbind(name);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
远程调用客户端:
public class RemoteClient {
public static void main(String[] args) {
try {
ContainerRemoteWave containerRemote =
(ContainerRemoteWave) Naming.lookup("rmi://127.0.0.1:4567/ContainerRemoteService");
List<SerializableContainer> scs = containerRemote.containers();
System.out.println("remote call result:" + scs);
if(scs == null) return ;
for(SerializableContainer sc : scs){
System.out.println("id:" + sc.getId() + ", " +
"name:" + sc.getName() + ", " +
"version:" + sc.getVersion() + ", " +
"time:" + sc.getTime());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}