利用動態(tài)代理實現(xiàn)簡單的RPC框架

RPC簡介


進程間通信(IPC):是在多任務(wù)操作系統(tǒng)或聯(lián)網(wǎng)的計算機之間運行的程序和進程所用的通信技術(shù)。有兩種類型的進程間通信(IPC)。

  1. 本地過程調(diào)用(LPC):LPC用在多任務(wù)操作系統(tǒng)中,使得同時運行的任務(wù)能互相會話。這些任務(wù)共享內(nèi)存空間使任務(wù)同步和互相發(fā)送信息。
  2. 遠程過程調(diào)用(RPC):RPC類似于LPC,只是在網(wǎng)上工作RPC開始是出現(xiàn)在Sun微系統(tǒng)公司和HP公司的運行UNIX操作系統(tǒng)的計算機中。

現(xiàn)在互聯(lián)網(wǎng)公司的系統(tǒng)都由許多大大小小的服務(wù)組成,各服務(wù)部署在不同的機器上,由不同的團隊負責(zé)。這時就會遇到兩個問題:
1)要搭建一個新服務(wù),免不了需要依賴他人的服務(wù),而現(xiàn)在他人的服務(wù)都在遠端,怎么調(diào)用?
2)其它團隊要使用我們的服務(wù),我們的服務(wù)該怎么發(fā)布以便他人調(diào)用?

假如現(xiàn)在有這樣一個接口,需要你實現(xiàn)后,提供給他人使用,如何提供給他呢?

package rpc;

/**
 * 客戶端和服務(wù)端公共的接口
 * <p>
 * 作者:余天然 on 2017/1/4 下午6:00
 */
public interface HelloService {
    String sayHello(String msg);
}

我們希望可以這樣
服務(wù)端實現(xiàn)接口:

package rpc;

/**
 * 作者:余天然 on 2017/1/4 下午10:30
 */
public class Server {

    /**
     * 服務(wù)端對接口的具體實現(xiàn)
     */
    public static class HelloServiceImpl implements HelloService {
        @Override
        public String sayHello(String msg) {
            String result = "hello world " + msg;
            System.out.println(result);
            return result;
        }
    }
}

然后客戶端直接調(diào)用接口:

package rpc;

/**
 * 作者:余天然 on 2017/1/4 下午10:30
 */
public class Client {

    public static void main(String[] args) {
        HelloService service = new Server.HelloServiceImpl();
        service.sayHello("直接調(diào)用");
    }
}

然而,這樣客戶端就直接依賴了服務(wù)端的HelloServiceImpl這個具體實現(xiàn)類,太耦合了!

客戶端和服務(wù)端之間應(yīng)該是依賴于接口,而不必依賴于具體的實現(xiàn)的。而且,客戶端和服務(wù)端往往在不同的機器上,這樣直接依賴肯定是不行的。那么,怎么辦呢?

下面該我們的RPC登場了!

1、RPC服務(wù)端

package rpc;

import java.io.IOException;

/**
 * 服務(wù)端
 * <p>
 * 作者:余天然 on 2017/1/4 下午6:27
 */
public class RpcServer {

    public static void main(String[] args) {
        try {
            //暴露服務(wù)
            HelloService service = new HelloServiceImpl();
            RpcFramework.export(service, 8989);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 服務(wù)端對接口的具體實現(xiàn)
     */
    private static class HelloServiceImpl implements HelloService {
        @Override
        public String sayHello(String msg) {
            String result = "hello world " + msg;
            System.out.println(result);
            return result;
        }
    }
}

2、RPC客戶端

package rpc;

/**
 * 客戶端
 * <p>
 * 作者:余天然 on 2017/1/4 下午6:02
 */
public class RpcClient {

    public static void main(String[] args) {
        try {
            //引用服務(wù)
            HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 8989);
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                String hello = service.sayHello("rpc" + i);
                System.out.println(hello);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

3、運行結(jié)果

服務(wù)端輸出:



客戶端輸出:


這里,客戶端并沒有依賴HelloServiceImpl這個類,為什么同樣也可以輸出“hello world rpc0”呢?
這就是我的這個簡單的RpcFramework的功勞了。

4、簡單的RPC框架

核心就是:動態(tài)代理+Socket

思路分析:

  1. 服務(wù)端暴露服務(wù),綁定一個端口,利用Socket輪詢,等待接受客戶端的請求。
  2. 客戶端引用服務(wù),利用動態(tài)代理,隱藏掉每個接口方法的實際調(diào)用。
  3. 客戶端將方法名、參數(shù)類型、方法所需參數(shù)傳給服務(wù)端,服務(wù)端接受到客戶端傳過來的方法名、參數(shù)類型、方法所需參數(shù)之后,利用反射,執(zhí)行具體的接口方法,然后將執(zhí)行結(jié)果返回給客戶端
package rpc;

import java.io.IOException;
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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 簡單的RPC框架
 * <p>
 * 動態(tài)代理+Socket
 * <p>
 * 作者:余天然 on 2017/1/4 下午5:59
 */
public class RpcFramework {

    private static ExecutorService executorService = Executors.newFixedThreadPool(20);

    /**
     * 服務(wù)端暴露服務(wù)
     *
     * @param service 服務(wù)實現(xiàn)
     * @param port    服務(wù)端口
     */
    public static void export(final Object service, int port) throws IOException {
        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);
        while (true) {
            final Socket socket = server.accept();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        try {
                            //服務(wù)端接受客戶端傳過來的方法名、參數(shù)類型、方法所需參數(shù),然后執(zhí)行方法
                            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();
                    }
                }
            });
        }
    }

    /**
     * 客戶端引用服務(wù)
     *
     * @param <T>            接口泛型
     * @param interfaceClass 接口類型
     * @param host           服務(wù)器主機名
     * @param port           服務(wù)器端口
     * @return 遠程服務(wù)
     * @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);

        //利用動態(tài)代理,對每個接口類的方法調(diào)用進行的隱藏
        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 {
                    //客戶端將方法名、參數(shù)類型、方法所需參數(shù)傳給服務(wù)端
                    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();
                }
            }
        });
    }
}

這里呢,我只是簡單的傳遞了方法名、參數(shù)類型、方法所需參數(shù)。

當需要完成更復(fù)雜的交互時,我們可以指定一個協(xié)議,然后由Server和Client根據(jù)該協(xié)議對數(shù)據(jù)的進行編碼解碼,根據(jù)協(xié)議內(nèi)容做出相應(yīng)的決策。

總而言之,RPC的核心是動態(tài)代理 。

客戶端看到的是接口的行為(這個行為沒有被實現(xiàn)),
服務(wù)端放的是接口行為的具體實現(xiàn)。

客戶端把行為和行為入?yún)⑻峁┙o服務(wù)端,然后服務(wù)端的接口實現(xiàn)執(zhí)行這個行為,最后再把執(zhí)行結(jié)果返回給客戶端。

看起來是客戶端執(zhí)行了行為,但其實是通過動態(tài)代理交給服務(wù)端執(zhí)行的。其中,行為和入?yún)⑦@些數(shù)據(jù)通過socket由客戶端傳給了服務(wù)端。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容