Java-进程通信RMI

RMI 是一种 Java 进程间通信的方式。

接口定义

首先,需要创建进程间通信的接口,需要继承 Remote :

1
2
3
4
5
6
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RobotKitService extends Remote{
public String roborResponse(String request) throws RemoteException;
}

服务端实现

服务端进程负责实现接口,需要继承 UnicastRemoteObject :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RobotService extends UnicastRemoteObject implements RobotKitService {
protected RobotService() throws RemoteException {
super();
}
@Override
public String roborResponse(String request) throws RemoteException {
System.out.println(request);
return "Success..";
}
}

以及,注册自身的 IP 地址和端口号:

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
try {
RobotService robotService = new RobotService();
LocateRegistry.createRegistry(9999);
Naming.rebind("rmi://127.0.0.1:9999/RobotService", robotService);
System.out.println("Server Start!");
} catch (RemoteException | MalformedURLException e) {
e.printStackTrace();
}
}

客户端实现

客户端进程直接通过 IP 地址和端口号获取接口实例,并进行调用:

1
2
3
4
5
6
try {
RobotKitService service = (RobotKitService)Naming.lookup("rmi://127.0.0.1:9999/RobotService");
String result = service.roborResponse(“test”);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
e.printStackTrace();
}

异常处理

1
no security manager: RMI class loader disabled

原因:服务端和客户端包名需要一致。

1
Caused by: java.lang.IllegalArgumentException: illegal remote method encountered

原因:Remote 接口定义的方法没有 throws RemoteException。

YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!