RMI和RPC区别联系
RMI
概念
RMI(Remote Method Invocation,远程方法调用)java1.2实现,实现了程序级不同jvm上的程序通信,是rpc的纯java版本。
场景
纯java通信的分布式通信解决方案。
stub->skeleton->找到真正的对象和方法->返回结果给stub
代码示例
客户端
public class Client {
public static void main(String[] args) {
Registry registry = null;
try {
registry = LocateRegistry.getRegistry("localhost", 8888);
ISayHello hello = (ISayHello)registry.lookup("hello");
String say = hello.say("andy");
System.out.println(say);
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}
服务端
public class Server {
public static void main(String[] args) {
Registry registry = null;
try {
ISayHello serverHello = new SayHelloImpl();
registry = LocateRegistry.createRegistry(8888);
registry.rebind("hello",serverHello);
System.out.println("serverHello启动...");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
接口
public interface ISayHello extends Remote {
String say(String name) throws RemoteException;
}
public class SayHelloImpl extends UnicastRemoteObject implements ISayHello{
protected SayHelloImpl() throws RemoteException {
super();
}
@Override
public String say(String name) throws RemoteException {
System.out.println("Hello " + name);
return "Hello " + name;
}
}
RPC
概念
RPC(Remote Procedure Call Protocol)远程过程调用协议,通过网络从远程计算机上请求调用某种服务。它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议。
场景
dubbo服务
代码
dubbo示例
// TODO
区别
**本质区别:**rmi是服务框架,rpc是网络协议。
语言限制:rmi只支持ava语言,rpc是网络服务协议,与语言无关。
**调用方式:**rmi在客户端通过stub向服务端进行远程接口调用,服务端的接口对客户端必须是可知的,不能调用不可知的服务;rpc通过网络协议向服务端发送了一个文本和参数集合,这样的classname.methodname(参数集)包含了类、方法、参数,服务端匹配到对应的服务就会返回结果。
**返回结果:**rmi返回的是java对象,rpc返回的是统一外部数据表示(External Data Representation,XDR)语言表示。