RMI(Remote Method Invocation),即远程方法调用。是Java官方的RPC实现。
RMI示例:
package io.github.baijifeilong.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface ISayHelloService extends Remote {
String hello(String name) throws RemoteException;
}
package io.github.baijifeilong.rmi;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
public class RmiServer {
public static void main(String[] args) throws RemoteException {
ISayHelloService sayHelloService = new SayHelloService();
UnicastRemoteObject.exportObject(sayHelloService, 0);
LocateRegistry.createRegistry(1099).rebind("SayHello", sayHelloService);
}
static class SayHelloService implements ISayHelloService {
@Override
public String hello(String name) {
return "hello, " + name;
}
}
}
package io.github.baijifeilong.rmi;
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 {
// RMI默认端口1099,不需要显式声明
Registry registry = LocateRegistry.getRegistry();
ISayHelloService sayHelloService = (ISayHelloService) registry.lookup("SayHello");
System.out.println(sayHelloService.hello("word"));
}
}
hello, word