MST

星途 面试题库

面试题:Java中RMI远程调用基础

请描述在Java中使用RMI实现远程调用时,服务端和客户端分别需要进行哪些主要步骤?
40.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

服务端主要步骤:

  1. 定义远程接口
    • 远程接口必须继承java.rmi.Remote接口。
    • 接口中的方法必须声明抛出java.rmi.RemoteException
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    
    public interface MyRemote extends Remote {
        String sayHello() throws RemoteException;
    }
    
  2. 实现远程接口
    • 实现类必须继承UnicastRemoteObject类,并实现远程接口。
    • 构造函数通常要抛出RemoteException
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    
    public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
        protected MyRemoteImpl() throws RemoteException {
            super();
        }
    
        @Override
        public String sayHello() throws RemoteException {
            return "Hello from RMI server!";
        }
    }
    
  3. 启动RMI注册服务
    • 可以在命令行使用rmiregistry命令启动,也可以在代码中启动。
    • 在代码中启动示例:
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;
    
    public class Server {
        public static void main(String[] args) {
            try {
                MyRemote service = new MyRemoteImpl();
                Registry registry = LocateRegistry.createRegistry(1099);
                registry.bind("MyRemoteService", service);
                System.out.println("Server started.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

客户端主要步骤:

  1. 获取远程对象引用
    • 通过Naming.lookup方法获取远程对象的引用,该方法接收远程对象的注册名称和URL。
    import java.rmi.Naming;
    import java.rmi.RemoteException;
    
    public class Client {
        public static void main(String[] args) {
            try {
                MyRemote service = (MyRemote) Naming.lookup("rmi://localhost:1099/MyRemoteService");
                String result = service.sayHello();
                System.out.println(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
  2. 调用远程方法
    • 使用获取到的远程对象引用调用远程接口中定义的方法,就像调用本地对象的方法一样,但要处理RemoteException异常。 在上述客户端代码中,通过service.sayHello()调用远程服务端的sayHello方法。