在eclipse环境下RMI的搭建过程:
(1)新建一个RMIServer工程作为服务端程序;
(2)在RMIServer工程中新建远程接口:
import java.rmi.Remote; import java.rmi.RemoteException; public interface ButterflyService extends Remote{ void execute(String message) throws RemoteException; }
它的包名可以任意,此例使用com.rmi.service
(3)在RMIServer工程中新建对远程接口的实现类:
import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import cn.com.nearme.rmi.service.ButterflyService; public class ButterflyServiceImpl extends UnicastRemoteObject implements ButterflyService { /** * */ private static final long serialVersionUID = 1L; public ButterflyServiceImpl() throws RemoteException { super(); // TODO Auto-generated constructor stub } @Override public void execute(String str) throws RemoteException { System.out.println(str); } }
(4)在RMIServer工程新建服务启动程序:
import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import com.rmi.service.ButterflyService; import com.rmi.service.impl.ButterflyServiceImpl; public class RMIServer { /** * @param args */ public static void main(String[] args) { try { ButterflyService service = new ButterflyServiceImpl(); LocateRegistry.createRegistry(1099); Naming.rebind("service", service); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
(5)将RMIServer中的com.rmi.service包导出为jar,命名为rmi.jar(可以任意)
(6)新建RMIClient工程,在该工程中新建类用于调用远程服务对象,同时新建lib目录将rmi.jar放置该目录,同时在工程中引用该jar:
import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.RemoteException; import com.rmi.service.ButterflyService; public class RMIClient { /** * @param args */ public static void main(String[] args) { try { ButterflyService service = (ButterflyService) Naming.lookup("service"); service.execute("helloword"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotBoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
(7)分别将RMIServer和RMIClient工程导出为可执行的jar,控制台先运行RMIServer.jar,然后运行RMIClient.jar,
可以看到运行RMIServer的控制打印出"helloworld",没运行一次RMIClient就显示一次。
此步骤没有按照RMI的标准过程,没有使用生成stub类和手动注册实例到RMI注册表。仅作为简易入门的参考