RMI是Java原生的分布式服务机制。支持Java对Java的分布式訪问。採用Java的序列化协议进行CodeC操作。

这里简单说下RMI公布服务和client引用服务的方式。


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");                        
                        //指定port
			Registry registry = LocateRegistry.createRegistry(8888); 
                        // 注冊服务
			registry.bind("demoservice",service);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("DemoService is running at Server");
	}
}


採用Naming工具类时,须要指定完整的URI方式时的服务名称。

值得注意的是。也须要先绑定port号。否则会报ConnectionRefuse的异常

public class Server {
	public static void main(String[] args){
		try {
			DemoService service = new DemoServiceImpl("ITer_ZC");
                        // 指定port
			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");
	}
}

採用JNDI的方式来公布RMI服务。须要指定完整的URI方式的服务名称

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");
	}
}


client引用RMI服务时,也能够採用两种方式来寻找服务,一种是RMI本身的类,一种是JNDI接口的类。

採用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


posted on 2017-04-26 18:49  lxjshuju  阅读(159)  评论(0)    收藏  举报