Java RMI(Remote Method Invocation)远程方法调用 详解

远程方法调用

Remote Method Invocation是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法。

编写一个RMI的步骤

  1. 定义一个远程接口,此接口需要继承java.rmi.Remote
  2. 开发远程接口的实现类
  3. 创建一个server并把远程对象注册到端口
  4. 创建一个client查找远程对象,调用远程方法

实例

定义一个远程接口
public interface RemoteHelloWord extends java.rmi.Remote {
  String sayHello() throws RemoteException;
}

为了处理远程方法发生的各种异常,每一个远程方法必须抛出一个java.rmi.RemoteException异常。

开发接口的实现类
public class RemoteHelloWordImpl  implements RemoteHelloWord {
    @Override
    public String sayHello() throws RemoteException {
        return "Hello Word!";
    }
}
创建一个Server并把对象注册到端口
  1. 创建并导出远程对象
  2. 用Java RMI registry 注册远程对象
public class RMIServer {
	public static void main(String[] args) {
	    try {
	        RemoteHelloWord hello=new RemoteHelloWordImpl();
	        RemoteHelloWord stub=(RemoteHelloWord)UnicastRemoteObject.exportObject(hello, 9999);
	        LocateRegistry.createRegistry(1099);
	        Registry registry=LocateRegistry.getRegistry();
	        registry.bind("helloword", stub);
	        System.out.println("绑定成功!");
	    } catch (RemoteException e) {
	        e.printStackTrace();
	    } catch (AlreadyBoundException e) {
	        e.printStackTrace();
	    }
	}
}
创建一个client查找远程对象,调用远程方法
public class RMIClient {
  public static void main(String[] args) {
         try {
              Registry registry = LocateRegistry.getRegistry("localhost");
              RemoteHelloWord hello = (RemoteHelloWord) registry.lookup( "helloword");
              String ret = hello.sayHello();
              System.out.println(ret);
        } catch (RemoteException e) {
               e.printStackTrace();
        } catch (NotBoundException e) {
               e.printStackTrace();
        }
  }

https://blog.csdn.net/a19881029/article/details/9465663
https://blog.csdn.net/lmy86263/article/details/72594760

发布了174 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/104966850