现在的位置: 首页 > 综合 > 正文

java之简单RMI远程方法调用的2种实现

2013年08月30日 ⁄ 综合 ⁄ 共 2328字 ⁄ 字号 评论关闭

RMI->remote method invoke 也就是远程方法调用

第一种 也是比较简单的方法 利用 UnicastRemoteObject

首先需要定义一个extents Remote 的接口  里面只有一个方法 测试用

public interface HelloRemoteInterface extends Remote
{
	public void hello() throws RemoteException;
}

下面要一个实现类 实现我们自己定义有RMI功能的接口 这个类不仅要实现接口 而且需要继承自UnicastRemoteObject

public class HelloRemoteIMPL extends UnicastRemoteObject implements HelloRemoteInterface
{
	protected HelloRemoteIMPL() throws RemoteException
	{
		super();
	}

	@Override
	public void hello() throws RemoteException
	{
		System.out.println("test RMI");
	}
}

下面就需要模拟一个server端和client端 首先是server端

public class RMIServer
{
	public static void main(String[] args) throws MalformedURLException, RemoteException, AlreadyBoundException
	{
		HelloRemoteIMPL h = new HelloRemoteIMPL(); 
		Registry reg = LocateRegistry.createRegistry(8888); 
		Naming.bind("rmi://localhost:8888/yang",h); 
	}
}

LocateRegistry.createRegistry(8888);
这一步是声明服务器RMI所使用的端口 也是必须的 默认值好像是1099

Naming.bind("rmi://localhost:8888/yang",h); 
绑定HelloRemoteIMPL 到服务器上

第一个参数为一个string型 有一个规范为 rmi + url + name 其中 rmi可以省略 也就是 rmi://localhost:8888/yang 等同于 //localhost:8888/yang

下面是client端  很简单

public class RMIClient
{
	public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException
	{
	  HelloRemoteInterface h =	(HelloRemoteInterface) Naming.lookup("rmi://localhost:8888/yang");
	  h.hello();
	}
}

但注意 这里调用时 只能转型为实现Remote的接口HelloRemoteInterface 而不能转化为实现了我们自己接口的类 HelloRemoteIMPL 

第二种 利用UnicastRemoteObject.exportObject()  代码稍多些

跟上面的套路差不多少 只不过我们的接口实现类HelloRemoteIMPL   不再需要继承 UnicastRemoteObject  改成

public class HelloRemoteIMPL  implements HelloRemoteInterface
{
	@Override
	public void hello() throws RemoteException
	{
		System.out.println("test RMI");
	}
}

server端 其中bind的规范和上面一样 如果是在本机 可以简写

public class RMIServer
{
	public static void main(String[] args) throws MalformedURLException, RemoteException, AlreadyBoundException
	{
		HelloRemoteIMPL h = new HelloRemoteIMPL();
		Registry reg = LocateRegistry.createRegistry(8888); 
		reg.bind("love", h);
		UnicastRemoteObject.exportObject(h);
	}
}

client端

public class RMIClient
{
	public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException
	{
		Registry reg=LocateRegistry.getRegistry("125.211.81.24",8888);
		HelloRemoteInterface h = (HelloRemoteInterface) reg.lookup("love");
		h.hello();
	}
}

稍微麻烦一点的就是我们的HelloRemoteIMPL  类需要一个又系统生成的HelloRemoteIMPL_Stub

方法为 cmd -> 到HelloRemoteIMPL  路径下 先javac编译HelloRemoteIMPL.java 然后
rmic HelloRemoteIMPL 
就可以产生出HelloRemoteIMPL

对应的 HelloRemoteIMPL_Stub

如果没有_Stub类的话会抛出 java.rmi.StubNotFoundException

抱歉!评论已关闭.