RMI:利用JDK中的Remote实现远程方法调用

 Java RMI:即Java远程方法调用,是针对Java语言的一种特殊RPC调用,一种用于实现远程过程调用的应用程序编程接口。下面用一个简单实例来说明Java RMI是怎样开发的。

步骤一:编写远程服务接口,该接口必须继承 java.rmi.Remote 接口,方法必须抛出 java.rmi.RemoteException 异常;

import java.rmi.Remote;
import java.rmi.RemoteException;

/** 
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:44:16 
*/
public interface IService extends Remote{
	String sayHello(String name) throws RemoteException;
}

步骤二:编写远程接口实现类,该实现类必须继承 java.rmi.server.UnicastRemoteObject 类;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

/** 
* 描述:
* @author zhengjl 
* @version 2019年1月21日 上午10:45:19 
*/
public class ServiceImpl extends UnicastRemoteObject implements IService{
	private static final long serialVersionUID = 1L;

	protected ServiceImpl() throws RemoteException {
		super();
	}

	@Override
	public String sayHello(String name) throws RemoteException{
		System.out.println("Hello " + name);
		return "Hello " + name;
	}

}

步骤三:启动一个RMI注册表,绑定端口。并且把需要对外暴漏的服务注册进注册表中

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/** 
* 描述:
* @author zhengjl 
* @version 2019年1月21日 上午10:47:43 
*/
public class Server {
	public static void main(String[] args) {
		Registry reg = null;
		try {
			reg = LocateRegistry.createRegistry(8888);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		try {
			IService server = new ServiceImpl();
			reg.rebind("hello", server);
			System.out.println("server bind...");
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}

服务启动,这时通过cmd查看端口,已经被监听:

步骤四:客户端查找远程对象,并调用远程方法

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/** 
* 描述:
* @author zhengjl
* @version 2019年1月21日 上午10:51:59 
*/
public class Client {
	public static void main(String[] args) {
		Registry reg = null;
		try {
			reg = LocateRegistry.getRegistry("127.0.0.1", 8888);
			String[] regList = reg.list();
			System.out.println("=====服务列表======");
			for (String r : regList) {
				System.out.println(r);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		try {
			IService hello = (IService) reg.lookup("hello");
			String result = hello.sayHello("stone");
			System.out.println("result from remote:"+result);
		} catch (RemoteException | NotBoundException e) {
			e.printStackTrace();
		}
	}
}

运行结果如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章