Java如何實現(xiàn)簡單的RPC框架
一、RPC簡介
RPC,全稱為Remote Procedure Call,即遠(yuǎn)程過程調(diào)用,它是一個計算機(jī)通信協(xié)議。它允許像調(diào)用本地服務(wù)一樣調(diào)用遠(yuǎn)程服務(wù)。它可以有不同的實現(xiàn)方式。如RMI(遠(yuǎn)程方法調(diào)用)、Hessian、Http invoker等。另外,RPC是與語言無關(guān)的。
RPC示意圖
如上圖所示,假設(shè)Computer1在調(diào)用sayHi()方法,對于Computer1而言調(diào)用sayHi()方法就像調(diào)用本地方法一樣,調(diào)用 –>返回。但從后續(xù)調(diào)用可以看出Computer1調(diào)用的是Computer2中的sayHi()方法,RPC屏蔽了底層的實現(xiàn)細(xì)節(jié),讓調(diào)用者無需關(guān)注網(wǎng)絡(luò)通信,數(shù)據(jù)傳輸?shù)燃?xì)節(jié)。
二、RPC框架的實現(xiàn)
上面介紹了RPC的核心原理:RPC能夠讓本地應(yīng)用簡單、高效地調(diào)用服務(wù)器中的過程(服務(wù))。它主要應(yīng)用在分布式系統(tǒng)。如Hadoop中的IPC組件。但怎樣實現(xiàn)一個RPC框架呢?
從下面幾個方面思考,僅供參考:
1.通信模型:假設(shè)通信的為A機(jī)器與B機(jī)器,A與B之間有通信模型,在Java中一般基于BIO或NIO;。
2.過程(服務(wù))定位:使用給定的通信方式,與確定IP與端口及方法名稱確定具體的過程或方法;
3.遠(yuǎn)程代理對象:本地調(diào)用的方法(服務(wù))其實是遠(yuǎn)程方法的本地代理,因此可能需要一個遠(yuǎn)程代理對象,對于Java而言,遠(yuǎn)程代理對象可以使用Java的動態(tài)對象實現(xiàn),封裝了調(diào)用遠(yuǎn)程方法調(diào)用;
4.序列化,將對象名稱、方法名稱、參數(shù)等對象信息進(jìn)行網(wǎng)絡(luò)傳輸需要轉(zhuǎn)換成二進(jìn)制傳輸,這里可能需要不同的序列化技術(shù)方案。如:protobuf,Arvo等。
三、Java實現(xiàn)RPC框架
1、實現(xiàn)技術(shù)方案
下面使用比較原始的方案實現(xiàn)RPC框架,采用Socket通信、動態(tài)代理與反射與Java原生的序列化。
2、RPC框架架構(gòu)
RPC架構(gòu)分為三部分:
1)服務(wù)提供者,運行在服務(wù)器端,提供服務(wù)接口定義與服務(wù)實現(xiàn)類。
2)服務(wù)中心,運行在服務(wù)器端,負(fù)責(zé)將本地服務(wù)發(fā)布成遠(yuǎn)程服務(wù),管理遠(yuǎn)程服務(wù),提供給服務(wù)消費者使用。
3)服務(wù)消費者,運行在客戶端,通過遠(yuǎn)程代理對象調(diào)用遠(yuǎn)程服務(wù)。
3、 具體實現(xiàn)
服務(wù)提供者接口定義與實現(xiàn),代碼如下:
public interface HelloService { String sayHi(String name); }
HelloServices接口實現(xiàn)類:
public class HelloServiceImpl implements HelloService { public String sayHi(String name) { return "Hi, " + name; } }
服務(wù)中心代碼實現(xiàn),代碼如下:
public interface Server { public void stop(); public void start() throws IOException; public void register(Class serviceInterface, Class impl); public boolean isRunning(); public int getPort(); }
服務(wù)中心實現(xiàn)類:
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.監(jiān)聽客戶端的TCP連接,接到TCP連接后將其封裝成task,由線程池執(zhí)行 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.將客戶端發(fā)送的碼流反序列化成對象,反射調(diào)用服務(wù)實現(xiàn)者,獲取執(zhí)行結(jié)果 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.將執(zhí)行結(jié)果反序列化,通過socket發(fā)送給客戶端 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(); } } } } } }
客戶端的遠(yuǎn)程代理對象:
public class RPCClient<T> { public static <T> T getRemoteProxyObj(final Class<?> serviceInterface, final InetSocketAddress addr) { // 1.將本地的接口調(diào)用轉(zhuǎn)換成JDK的動態(tài)代理,在動態(tài)代理中實現(xiàn)接口的遠(yuǎn)程調(diào)用 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.創(chuàng)建Socket客戶端,根據(jù)指定地址連接遠(yuǎn)程服務(wù)提供者 socket = new Socket(); socket.connect(addr); // 3.將遠(yuǎn)程服務(wù)調(diào)用所需的接口類、方法名、參數(shù)列表等編碼后發(fā)送給服務(wù)提供者 output = new ObjectOutputStream(socket.getOutputStream()); output.writeUTF(serviceInterface.getName()); output.writeUTF(method.getName()); output.writeObject(method.getParameterTypes()); output.writeObject(args); // 4.同步阻塞等待服務(wù)器返回應(yīng)答,獲取應(yīng)答后返回 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")); } }
運行結(jié)果:
regeist service HelloService
start server
Hi, test
四、總結(jié)
RPC本質(zhì)為消息處理模型,RPC屏蔽了底層不同主機(jī)間的通信細(xì)節(jié),讓進(jìn)程調(diào)用遠(yuǎn)程的服務(wù)就像是本地的服務(wù)一樣。
五、可以改進(jìn)的地方
這里實現(xiàn)的簡單RPC框架是使用Java語言開發(fā),與Java語言高度耦合,并且通信方式采用的Socket是基于BIO實現(xiàn)的,IO效率不高,還有Java原生的序列化機(jī)制占內(nèi)存太多,運行效率也不高??梢钥紤]從下面幾種方法改進(jìn)。
- 可以采用基于JSON數(shù)據(jù)傳輸?shù)腞PC框架;
- 可以使用NIO或直接使用Netty替代BIO實現(xiàn);
- 使用開源的序列化機(jī)制,如Hadoop Avro與Google protobuf等;
- 服務(wù)注冊可以使用Zookeeper進(jìn)行管理,能夠讓應(yīng)用更加穩(wěn)定。
以上就是Java如何實現(xiàn)簡單的RPC框架的詳細(xì)內(nèi)容,更多關(guān)于Java實現(xiàn)RPC框架的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java使用OpenFeign管理多個第三方服務(wù)調(diào)用
最近開發(fā)了一個統(tǒng)一調(diào)度類的項目,需要依賴多個第三方服務(wù),這些服務(wù)都提供了HTTP接口供我調(diào)用。感興趣的可以了解一下2021-06-06mybatis-plus分頁如何接收前端參數(shù)limit和page
這篇文章主要介紹了mybatis-plus分頁如何接收前端參數(shù)limit和page,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01springboot無法從靜態(tài)上下文中引用非靜態(tài)變量的解決方法
這篇文章主要介紹了springboot無法從靜態(tài)上下文中引用非靜態(tài)變量的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-06-06淺談Java中Lambda表達(dá)式的相關(guān)操作
java8新特性,Lambda是一個匿名函數(shù),類似Python中的Lambda表達(dá)式、js中的箭頭函數(shù),目的簡化操作,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06SpringBoot中默認(rèn)緩存實現(xiàn)方案的示例代碼
這篇文章主要介紹了SpringBoot中默認(rèn)緩存實現(xiàn)方案,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08