動態代理系列(擴展篇)RPC實現原理

本文轉載自:扒一扒RPC

因爲RPC是基於動態代理的。想必大家都聽過RPC,但是可能並沒有針對的去了解過,因此本文打算以如下結構講一講RPC:

①儘量淺顯易懂的描述RPC的工作原理。

②分析一個RPC的Demo。

##一、 走近RPC

###1.1 什麼是RPC

RPC是Remote Procedure Call的縮寫,即遠程過程調用,意思是可以在一臺機器上調用遠程的服務。在非分佈式環境下,我們的程序調用服務都是本地調用,但是隨着分佈式結構的普遍,越來越多的應用需要解耦,將不同的獨立功能部署發佈成不同的服務供客戶端調用。RPC就是爲了解決這個問題的。

###1.2 RPC原理

首先,我們心裏帶着這樣的問題:要怎麼樣去調用遠程的服務呢?

①肯定要知道IP和端口吧(確定唯一一個進程)
②肯定要知道調用什麼服務吧(方法名和參數)
③調用服務後可能需要結果吧。

這三點又怎麼實現呢?往下看:

RPC的設計由Client,Client stub,Network ,Server stub,Server構成

其中Client就是用來調用服務的,Cient stub是用來把調用的方法和參數序列化的(因爲要在網絡中傳輸,必須要把對象轉變成字節),Network用來傳輸這些信息到Server stubServer stub用來把這些信息反序列化的,Server就是服務的提供者,最終調用的就是Server提供的方法。

RPC的結構如下圖:

這裏寫圖片描述

圖中1-10序號的含義如下:

(1) Client像調用本地服務似的調用遠程服務;
(2) Client stub接收到調用後,將方法、參數序列化
(3) 客戶端通過sockets將消息發送到服務端
(4) Server stub 收到消息後進行解碼(將消息對象反序列化)
(5) Server stub 根據解碼結果調用本地的服務
(6) 本地服務執行(對於服務端來說是本地執行)並將結果返回給Server stub
(7) Server stub將返回結果打包成消息(將結果消息對象序列化)
(8) 服務端通過sockets將消息發送到客戶端
(9) Client stub接收到結果消息,並進行解碼(將結果消息發序列化)
(10) 客戶端得到最終結果。

##二、簡單RPC程序

在瞭解了RPC的大致原理之後,我們給出RPC的示例。這裏直接引用梁飛大神的代碼,後面給出代碼分析:

###2.1 核心框架類

/*
 * Copyright 2011 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.study.rpc.framework;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * RpcFramework
 * 
 * @author william.liangf
 */
public class RpcFramework {
    /**
     * 暴露服務
     * 
     * @param service 服務實現
     * @param port 服務端口
     * @throws Exception
     */
    public static void export(final Object service, int port) throws Exception {
        if (service == null)
            throw new IllegalArgumentException("service instance == null");
        if (port <= 0 || port > 65535)
            throw new IllegalArgumentException("Invalid port " + port);
        System.out.println("Export service " + service.getClass().getName() + " on port " + port);
        ServerSocket server = new ServerSocket(port);
        for(;;) {
            try {
                final Socket socket = server.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            try {
                                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                                try {
                                    String methodName = input.readUTF();
                                    Class<?>[] parameterTypes = (Class<?>[])input.readObject();
                                    Object[] arguments = (Object[])input.readObject();
                                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                                    try {
                                        Method method = service.getClass().getMethod(methodName, parameterTypes);
                                        Object result = method.invoke(service, arguments);
                                        output.writeObject(result);
                                    } catch (Throwable t) {
                                        output.writeObject(t);
                                    } finally {
                                        output.close();
                                    }
                                } finally {
                                    input.close();
                                }
                            } finally {
                                socket.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 引用服務
     * 
     * @param <T> 接口泛型
     * @param interfaceClass 接口類型
     * @param host 服務器主機名
     * @param port 服務器端口
     * @return 遠程服務
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
        if (interfaceClass == null)
            throw new IllegalArgumentException("Interface class == null");
        if (! interfaceClass.isInterface())
            throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
        if (host == null || host.length() == 0)
            throw new IllegalArgumentException("Host == null!");
        if (port <= 0 || port > 65535)
            throw new IllegalArgumentException("Invalid port " + port);
        System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
                Socket socket = new Socket(host, port);
                try {
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                    try {
                        output.writeUTF(method.getName());
                        output.writeObject(method.getParameterTypes());
                        output.writeObject(arguments);
                        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                        try {
                            Object result = input.readObject();
                            if (result instanceof Throwable) {
                                throw (Throwable) result;
                            }
                            return result;
                        } finally {
                            input.close();
                        }
                    } finally {
                        output.close();
                    }
                } finally {
                    socket.close();
                }
            }
        });
    }
}


###2.2 定義服務接口

/*
 * Copyright 2011 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.study.rpc.test;
/**
 * HelloService
 * 
 * @author william.liangf
 */
public interface HelloService {
    String hello(String name);
}

###2.3 實現服務

/*
 * Copyright 2011 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.study.rpc.test;
/**
 * HelloServiceImpl
 * 
 * @author william.liangf
 */
public class HelloServiceImpl implements HelloService {
    public String hello(String name) {
        return "Hello " + name;
    }
}

###2.4 暴露服務

/*
 * Copyright 2011 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.study.rpc.test;
import com.alibaba.study.rpc.framework.RpcFramework;
/**
 * RpcProvider
 * 
 * @author william.liangf
 */
public class RpcProvider {
    public static void main(String[] args) throws Exception {
        HelloService service = new HelloServiceImpl();
        RpcFramework.export(service, 1234);
    }
}


###2.5 引用服務

/*
 * Copyright 2011 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.alibaba.study.rpc.test;
import com.alibaba.study.rpc.framework.RpcFramework;
/**
 * RpcConsumer
 * 
 * @author william.liangf
 */
public class RpcConsumer {
    public static void main(String[] args) throws Exception {
        HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
        for (int i = 0; i < Integer.MAX_VALUE; i ++) {
            String hello = service.hello("World" + i);
            System.out.println(hello);
            Thread.sleep(1000);
        }
    }
}

代碼寫的簡單清晰又很能說明問題,不得不佩服大佬的技術。回過頭來,我們分析一下這個程序的結構。
再次把RPC的5個組成部分回顧一下:Cient, Client-stub, Network, Server,Server-stub。
首先2.2定義服務接口和2.3實現服務都是在Server端實現的。寫完了服務之後需要發佈出去,以供客戶端調用。於是在2.4暴露服務中調用export方法把服務發佈出去。export有一個參數是服務實現的對象service,這就給客戶端提供了調用的可能性。我們看看export裏都做了什麼:

ServerSocket server = new ServerSocket(port); 創建ServerSocket並綁定接口。 然後是個無限循環,因爲一直提供服務嘛,final Socket socket = server.accept(); 以阻塞的方式監聽網絡連接。開一個線程去處理客戶端發過來的信息(反序列化方法名,參數類型,參數對象),這部分功能相當於Server-stub。然後通過反射機制調用服務對象的方法,並把得到的結果序列化返回給客戶端。

看客戶端,也就是2.5引用服務。通過refer函數得到服務的對象(這個對象就是通過動態代理生成的代理對象)。然後像調用本地方法一樣調用遠程方法。我們看下refer裏都做了什麼:

return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler()
{...重寫invoke方法})

主要是返回服務實現類的代理對象,我們在分析JDK動態代理的時候知道,當我們調用代理對象的方法時,invoke方法會被執行。在invoke方法中, Socket socket = new Socket(host, port); 創建Socket與服務器取得連接。然後將方法名,方法類型,方法參數序列化發給服務器端,這部分功能相當於Client-stub。然後獲得服務器端發送過來的結果。

這樣RPC的功能就實現了。

本文轉載自:扒一扒RPC

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章