面试题答案
一键面试服务端主要步骤:
- 定义远程接口:
- 远程接口必须继承
java.rmi.Remote
接口。 - 接口中的方法必须声明抛出
java.rmi.RemoteException
。
import java.rmi.Remote; import java.rmi.RemoteException; public interface MyRemote extends Remote { String sayHello() throws RemoteException; }
- 远程接口必须继承
- 实现远程接口:
- 实现类必须继承
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!"; } }
- 实现类必须继承
- 启动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(); } } }
- 可以在命令行使用
客户端主要步骤:
- 获取远程对象引用:
- 通过
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(); } } }
- 通过
- 调用远程方法:
- 使用获取到的远程对象引用调用远程接口中定义的方法,就像调用本地对象的方法一样,但要处理
RemoteException
异常。 在上述客户端代码中,通过service.sayHello()
调用远程服务端的sayHello
方法。
- 使用获取到的远程对象引用调用远程接口中定义的方法,就像调用本地对象的方法一样,但要处理