标签:rpc
RMI是Java原生的分布式服务机制,支持Java对Java的分布式访问,采用Java的序列化协议进行CodeC操作。这里简单说下RMI发布服务和客户端引用服务的方式。
RMI发布服务时支持两种方式,一种是RMI本身的发布协议,另外一种是采用通用的JNDI的方式来发布服务。
采用JMI本身的发布协议,可以使用Registry接口,也可以使用Naming工具类。
使用Registry接口时,bind的服务名称只需要直接写服务名称就行,RMI内部会把它变成rmi://ip:port/servicename的方式
public class Server { public static void main(String[] args){ try { DemoService service = new DemoServiceImpl("ITer_ZC"); //指定端口 Registry registry = LocateRegistry.createRegistry(8888); // 注册服务 registry.bind("demoservice",service); } catch (Exception e) { e.printStackTrace(); } System.out.println("DemoService is running at Server"); } }
public class Server { public static void main(String[] args){ try { DemoService service = new DemoServiceImpl("ITer_ZC"); // 指定端口 LocateRegistry.createRegistry(8888); //完整的URI方式的服务名称 Naming.bind("rmi://10.2.43.50:8888/demoservice",service); } catch (Exception e) { e.printStackTrace(); } System.out.println("DemoService is running at Server"); } }
public class Server { public static void main(String[] args){ try { DemoService service = new DemoServiceImpl("ITer_ZC"); Registry registry = LocateRegistry.createRegistry(8888); Context nameContext = new InitialContext(); nameContext.rebind("rmi://10.2.43.50:8888/demoservice", service); } catch (Exception e) { e.printStackTrace(); } System.out.println("DemoService is running at Server"); } }
采用RMI本身的类来引用RMI服务
public class Client { public static void main(String[] args){ String url = "rmi://10.2.43.50:8888/demoservice"; try { DemoService service = (DemoService)Naming.lookup(url); System.out.println(service.sayHi()); } catch (Exception e) { e.printStackTrace(); } } }
采用JNDI接口来引用RMI服务
public class Client { public static void main(String[] args){ String url = "rmi://10.2.43.50:8888/demoservice"; Context nameContext; try { nameContext = new InitialContext(); DemoService service = (DemoService)nameContext.lookup(url); System.out.println(service.sayHi()); } catch (Exception e) { e.printStackTrace(); } } }
转载请注明来源: http://blog.csdn.net/iter_zc
标签:rpc
原文地址:http://blog.csdn.net/iter_zc/article/details/40186577