java中进行远程方法调用,能支持分布式计算。并且可以实现在server的修改,能反应到各个client。
假如server的ip是:192.168.11.2,
server端的代码如下:
/** * */ package com.vs.rmi; import java.rmi.Remote; import java.rmi.RemoteException; public interface Product extends Remote { public String getDescription() throws RemoteException; }
package com.vs.rmi; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class ProductImpl extends UnicastRemoteObject implements Product { private String name; public ProductImpl() throws RemoteException { super(); name = "my rmi"; } @Override public String getDescription() throws RemoteException { return "hello world, " + name; } }
/** * */ package com.vs.rmi; import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; /** * @author hadoop * */ public class ProductServer { /** * @param args */ public static void main(String[] args) { /* * 创建和安装一个安全管理器,令其支持 RMI. 作为 Java 开发包的一部分 * * 适用于 RMI 唯一一个是 RMISecurityManager. * * * * if(System.getSecurityManager() == null) { * * System.setSecurityManager(new RMISecurityManager()); * * } */ try { LocateRegistry.createRegistry(8808); ProductImpl server = new ProductImpl(); Naming.rebind("//192.168.11.2:8808/SAMPLE-SERVER", server); System.out.println("远程对象注册成功, RMI 服务已经启动,等待客户端调用 ...."); } catch (java.net.MalformedURLException me) { System.out.println("Malformed URL:" + me.toString()); } catch (RemoteException re) { System.out.println("Remote exception:" + re.toString()); } } }
Project接口必须打成jar包,在client的包中进行引入。
client端的代码如下:
package com.vs.myrmi; import java.rmi.*; import com.vs.rmi.Product; public class RmiSampleClient { public static void main(String[] args) { try { String url = "//192.168.11.2:8808/SAMPLE-SERVER"; Product product = (Product)Naming.lookup(url); System.out.println(product.getDescription()); } catch (RemoteException exc) { System.out.println("Error in lookup: " + exc.toString()); } catch (java.net.MalformedURLException exc) { System.out.println("Malformed URL: " + exc.toString()); } catch (java.rmi.NotBoundException exc) { System.out.println("NotBound: " + exc.toString()); } } }
先执行server端进行监听,然后执行client端,client执行的结果如下:
hello world, my rmi
java1.6中,已经不需要手动使用rmic命令生成骨架。