Skip to content

RMI

date
2023-09-10 12:08:13

Java RMI ( Remote Method Invocation ) 远程方法调用,它允许在一个 Java 虚拟机中运行的对象调用在另一个 Java 虚拟机中运行的对象上的方法。

RMI 分布式应用程序:

  • RMI Server :创建一些远程对象
  • Registry :服务端调用注册表以将名称与远程对象关联
  • RMI Client:客户端在服务器的注册表中按名称查找远程对象,然后对其调用方法

动态类加载:

image-20230903160628546

简单实现

服务端

继承 Remote 的接口,服务端、客户端都要有这个接口,服务端需要实现该接口。

1
2
3
4
5
6
7
8
9
package org.example;

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

public interface IRemoteObj extends Remote {
    // 客户端要远程调用的方法
    public String sayHello(String name) throws RemoteException;
}
package org.example;

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

// 实现 IRemoteObj
public class remoteObj extends UnicastRemoteObject implements IRemoteObj {
    public remoteObj() throws RemoteException {
    }

    @Override
    public String sayHello(String name) {
        String str = "hello " + name + " !";
        return str;
    }
}
package org.example;

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

public class rmiServer {
    public static void main(String[] args) throws RemoteException, AlreadyBoundException {
        // 创建远程对象
        IRemoteObj remoteObj = new remoteObj();
        // 创建注册中心
        Registry r = LocateRegistry.createRegistry(1099);
        // 绑定到注册中心
        r.bind("remoteObj",remoteObj);
        System.out.println("Start...");
    }
}

客户端

1
2
3
4
5
6
7
8
9
package org.example;

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

public interface IRemoteObj extends Remote {
    public String sayHello(String name) throws RemoteException;

}
package org.example;

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

public class rmiClient {
    public static void main(String[] args) throws RemoteException, NotBoundException {
        // 获取注册中心
        Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
        // 查找,获取远程方法
        IRemoteObj remoteObj = (IRemoteObj) registry.lookup("remoteObj");
        // 调用远程方法
        System.out.println(remoteObj.sayHello("fuming"));
    }
}

未完待续 ...