一、RPC簡介
RPC,全稱為Remote Procedure Call,即遠程過程調用,它是一個計算機通信協議。它允許像調用本地服務一樣調用遠程服務。它可以有不同的實現方式。如RMI(遠程方法調用)、Hessian、Http invoker等。另外,RPC是與語言無關的。
PC概述
RPC(Remote Procedure Call)即遠程過程調用,允許一台計算機調用另一台計算機上的程序得到結果,而代碼中不需要做額外的編程,就像在本地調用一樣。
現在互聯網應用的量級越來越大,單台計算機的能力有限,需要借助可擴展的計算機集群來完成,分布式的應用可以借助RPC來完成機器之間的調用。
RPC框架原理
在RPC框架中主要有三個角色:Provider、Consumer和Registry。如下圖所示:
節點角色說明:
* Server: 暴露服務的服務提供方。
* Client: 調用遠程服務的服務消費方。
* Registry: 服務注冊與發現的注冊中心。
RPC示意圖
如上圖所示,假設Computer1在調用sayHi()方法,對於Computer1而言調用sayHi()方法就像調用本地方法一樣,調用 –>返回。但從后續調用可以看出Computer1調用的是Computer2中的sayHi()方法,RPC屏蔽了底層的實現細節,讓調用者無需關注網絡通信,數據傳輸等細節。
一次完整的RPC調用流程(同步調用,異步另說)如下:
1)服務消費方(client)調用以本地調用方式調用服務;
2)client stub接收到調用后負責將方法、參數等組裝成能夠進行網絡傳輸的消息體;
3)client stub找到服務地址,並將消息發送到服務端;
4)server stub收到消息后進行解碼;
5)server stub根據解碼結果調用本地的服務;
6)本地服務執行並將結果返回給server stub;
7)server stub將返回結果打包成消息並發送至消費方;
8)client stub接收到消息,並進行解碼;
9)服務消費方得到最終結果。
RPC框架的目標就是要2~8這些步驟都封裝起來,讓用戶對這些細節透明。
服務注冊&發現
服務提供者啟動后主動向注冊中心注冊機器ip、port以及提供的服務列表;
服務消費者啟動時向注冊中心獲取服務提供方地址列表,可實現軟負載均衡和Failover;
使用到的技術
1、動態代理
生成 client stub和server stub需要用到 Java 動態代理技術 ,我們可以使用JDK原生的動態代理機制,可以使用一些開源字節碼工具框架 如:CgLib、Javassist等。
2、序列化
為了能在網絡上傳輸和接收 Java對象,我們需要對它進行 序列化和反序列化操作。
* 序列化:將Java對象轉換成byte[]的過程,也就是編碼的過程;
* 反序列化:將byte[]轉換成Java對象的過程;
可以使用Java原生的序列化機制,但是效率非常低,推薦使用一些開源的、成熟的序列化技術,例如:protobuf、Thrift、hessian、Kryo、Msgpack
關於序列化工具性能比較可以參考:jvm-serializers
3、NIO
當前很多RPC框架都直接基於netty這一IO通信框架,比如阿里巴巴的HSF、dubbo,Hadoop Avro,推薦使用Netty 作為底層通信框架。
4、服務注冊中心
可選技術:
* Redis
* Zookeeper
* Consul
* Etcd
二、RPC框架的實現
上面介紹了RPC的核心原理:RPC能夠讓本地應用簡單、高效地調用服務器中的過程(服務)。它主要應用在分布式系統。如Hadoop中的IPC組件。但怎樣實現一個RPC框架呢?
從下面幾個方面思考,僅供參考:
1.通信模型:假設通信的為A機器與B機器,A與B之間有通信模型,在Java中一般基於BIO或NIO;。
2.過程(服務)定位:使用給定的通信方式,與確定IP與端口及方法名稱確定具體的過程或方法;
3.遠程代理對象:本地調用的方法(服務)其實是遠程方法的本地代理,因此可能需要一個遠程代理對象,對於Java而言,遠程代理對象可以使用Java的動態對象實現,封裝了調用遠程方法調用;
4.序列化,將對象名稱、方法名稱、參數等對象信息進行網絡傳輸需要轉換成二進制傳輸,這里可能需要不同的序列化技術方案。如:protobuf,Arvo等。
三、Java實現RPC框架
1、實現技術方案
下面使用比較原始的方案實現RPC框架,采用Socket通信、動態代理與反射與Java原生的序列化。
2、RPC框架架構
RPC架構分為三部分:
1)服務提供者,運行在服務器端,提供服務接口定義與服務實現類。
2)服務中心,運行在服務器端,負責將本地服務發布成遠程服務,管理遠程服務,提供給服務消費者使用。
3)服務消費者,運行在客戶端,通過遠程代理對象調用遠程服務。
3、 具體實現
服務提供者接口定義與實現,代碼如下:
public interface HelloService { String sayHi(String name); }
HelloServices接口實現類:
public class HelloServiceImpl implements HelloService { public String sayHi(String name) { return "Hi, " + name; } }
服務中心代碼實現,代碼如下:
public interface Server { public void stop(); public void start() throws IOException; public void register(Class serviceInterface, Class impl); public boolean isRunning(); public int getPort(); }
服務中心實現類:
public class ServiceCenter implements Server { private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private static final HashMap<String, Class> serviceRegistry = new HashMap<String, Class>(); private static boolean isRunning = false; private static int port; public ServiceCenter(int port) { this.port = port; } public void stop() { isRunning = false; executor.shutdown(); } public void start() throws IOException { ServerSocket server = new ServerSocket(); server.bind(new InetSocketAddress(port)); System.out.println("start server"); try { while (true) { // 1.監聽客戶端的TCP連接,接到TCP連接后將其封裝成task,由線程池執行 executor.execute(new ServiceTask(server.accept())); } } finally { server.close(); } } public void register(Class serviceInterface, Class impl) { serviceRegistry.put(serviceInterface.getName(), impl); } public boolean isRunning() { return isRunning; } public int getPort() { return port; } private static class ServiceTask implements Runnable { Socket clent = null; public ServiceTask(Socket client) { this.clent = client; } public void run() { ObjectInputStream input = null; ObjectOutputStream output = null; try { // 2.將客戶端發送的碼流反序列化成對象,反射調用服務實現者,獲取執行結果 input = new ObjectInputStream(clent.getInputStream()); String serviceName = input.readUTF(); String methodName = input.readUTF(); Class<?>[] parameterTypes = (Class<?>[]) input.readObject(); Object[] arguments = (Object[]) input.readObject(); Class serviceClass = serviceRegistry.get(serviceName); if (serviceClass == null) { throw new ClassNotFoundException(serviceName + " not found"); } Method method = serviceClass.getMethod(methodName, parameterTypes); Object result = method.invoke(serviceClass.newInstance(), arguments); // 3.將執行結果反序列化,通過socket發送給客戶端 output = new ObjectOutputStream(clent.getOutputStream()); output.writeObject(result); } catch (Exception e) { e.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } if (clent != null) { try { clent.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
客戶端的遠程代理對象:
public class RPCClient<T> { public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) { // 1.將本地的接口調用轉換成JDK的動態代理,在動態代理中實現接口的遠程調用 return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Socket socket = null; ObjectOutputStream output = null; ObjectInputStream input = null; try { // 2.創建Socket客戶端,根據指定地址連接遠程服務提供者 socket = new Socket(); socket.connect(addr); // 3.將遠程服務調用所需的接口類、方法名、參數列表等編碼后發送給服務提供者 output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF(serviceInterface.getName()); output.writeUTF(method.getName()); output.writeObject(method.getParameterTypes()); output.writeObject(args); // 4.同步阻塞等待服務器返回應答,獲取應答后返回 input = new ObjectInputStream(socket.getInputStream()); return input.readObject(); } finally { if (socket != null) socket.close(); if (output != null) output.close(); if (input != null) input.close(); } } }); } }
最后為測試類:
public class RPCTest { public static void main(String[] args) throws IOException { new Thread(new Runnable() { public void run() { try { Server serviceServer = new ServiceCenter(8088); serviceServer.register(HelloService.class, HelloServiceImpl.class); serviceServer.start(); } catch (IOException e) { e.printStackTrace(); } } }).start(); HelloService service = RPCClient.getRemoteProxyObj(HelloService.class, new InetSocketAddress("localhost", 8088)); System.out.println(service.sayHi("test")); } }
運行結果:
regeist service HelloService
start server
Hi, test
四、總結
RPC本質為消息處理模型,RPC屏蔽了底層不同主機間的通信細節,讓進程調用遠程的服務就像是本地的服務一樣。
五、可以改進的地方
這里實現的簡單RPC框架是使用Java語言開發,與Java語言高度耦合,並且通信方式采用的Socket是基於BIO實現的,IO效率不高,還有Java原生的序列化機制占內存太多,運行效率也不高。可以考慮從下面幾種方法改進。
- 可以采用基於JSON數據傳輸的RPC框架;
- 可以使用NIO或直接使用Netty替代BIO實現;
- 使用開源的序列化機制,如Hadoop Avro與Google protobuf等;
- 服務注冊可以使用Zookeeper進行管理,能夠讓應用更加穩定。