RMI 接口Demo
简单的分布式rmi接口写法,共4文件
1. 业务接口
package com.sk.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/*此接口继承 Remote接口
供远程客户调用的方法都在这样公开(暴露)
每一个方法都抛出RemoteException
*/
public interface PerfectTime extends Remote{
long getPerfectTime() throws RemoteException;
}
2. 业务接口实现
package com.sk.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/*
业务接口的具体实现
*/
public class PerfectTimeBean extends UnicastRemoteObject implements PerfectTime{
//必须具备显式构造函数,并抛出RemoteException
protected PerfectTimeBean() throws RemoteException { }
private static final long serialVersionUID = 1L ;
public long getPerfectTime() throws RemoteException {
// TODO Auto-generated method stub
return System.currentTimeMillis();
}
}
3. rmi服务端
package com.sk.rmi;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/*
Rmi服务端方法,执行rmi服务端的机器将变为rmi服务器,提供给客户端rmi远程对象,从而调用暴露的远程方法
*/
public class PerfectTimeServer {
public static void main(String[] args) throws RemoteException, MalformedURLException, AlreadyBoundException {
//声明业务接口
PerfectTime pt=new PerfectTimeBean();
//LocateRegistry用户提供命名服务,创建命名服务,2008为端口
Registry registry=LocateRegistry.createRegistry(2008);
// registry.bind("task", pt);
//同注释的效果一样
Naming.rebind("rmi://localhost:2008/task", pt);
System.out.println("Ready ");
}
}
4. rmi客户端
package com.sk.rmi;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/*
Rmi客户端
*/
public class PerfectTimeClient {
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
// System.setSecurityManager(new RMISecurityManager());
// PerfectTime pt = (PerfectTime)Naming.lookup("//127.0.0.1:2008/task");
PerfectTime pt =(PerfectTime)LocateRegistry.getRegistry(2008).lookup("task");
System.out.println("server Time is:"+pt.getPerfectTime());
}
}
将4个java源文件编译生成class文件,用rmic 编译 PerfectTimeBean.class文件,由于有包结构了,所有直接将包 com.sk.rmi拷到 Java/jdk 1.5.0 _02/bin下,执行rmic –vcompat com.sk.rmi.PerfectTimeBean将生成PerfectTimeBean_Skel.class, PerfectTimeBean_Stub.class2个class文件,
运行rmiregistry.exe
运行PerfectTimeServer
运行 PerfectTimeClient,即可调用rmi服务端方法