手寫(xiě)簡(jiǎn)單的RPC框架

什么是RPC?

image.png

優(yōu)點(diǎn):將功能解耦,性能稍高,可擴(kuò)展性和可維護(hù)性,高可用(負(fù)載均衡,自動(dòng)重試)
缺點(diǎn):復(fù)雜,運(yùn)維難度大,跨平臺(tái)/語(yǔ)言調(diào)用麻煩

代碼目錄結(jié)構(gòu):


image.png

GreetingService接口

public interface GreeatingService {
    public String sayHi(String s);
}

GreetingService接口實(shí)現(xiàn)類

public class GreetingServiceImpl implements GreeatingService {
    @Override
    public String sayHi(String s) {
        return s;
    }
}

客戶端

public class Application {
    public static void main(String[] args) throws IOException {
        GreeatingService service = new MyDubboClient<>(GreeatingService.class).getRef();
        System.out.println(service.sayHi("gebilaowang"));
    }
}

服務(wù)端

public class Application {
    public static void main(String[] args) throws IOException {
        new MyDubboProvider<>(new GreetingServiceImpl()).start();
        System.in.read();
    }
}

客戶端具體實(shí)現(xiàn)類

public class MyDubboClient<T> {
    private Class<T> interfaceClass;
    private Socket socket;

    public MyDubboClient(Class<T> interfaceClass) throws IOException {
        this.interfaceClass = interfaceClass;
        this.socket = new Socket();
        this.socket.connect(new InetSocketAddress("127.0.0.1", 8888));
    }

    public T getRef() {
        return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        MethodInfo info = new MethodInfo(method.getName(),
                                Stream.of(args).collect(Collectors.toList()));
                        MyDubboClient.this.socket.getOutputStream().write((JSON.toJSON(info) + "\n").getBytes());
                        MyDubboClient.this.socket.getOutputStream().flush();
                        System.out.println("sent!");

                        String returnValueJSON = new BufferedReader(new InputStreamReader(MyDubboClient.this.socket.getInputStream())).readLine();
                        System.out.println("Get: " + returnValueJSON);
                        return JSON.parse(returnValueJSON);
                    }
                });
    }
}

服務(wù)端具體實(shí)現(xiàn)類:

package lib;

import com.alibaba.fastjson.JSON;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class MyDubboProvider<T> {
    private T serviceImpl;
    private ServerSocket serverSocket;

    public MyDubboProvider(T serviceImpl) throws IOException {
        this.serviceImpl = serviceImpl;
        this.serverSocket = new ServerSocket(8888);
    }

    public void start() throws IOException {
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("Accept!");
            new WorkerThread(socket).start();
        }
    }

    private class WorkerThread extends Thread {
        private Socket socket;

        public WorkerThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                String line = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
                System.out.println(line);
                MethodInfo methodInfo = JSON.parseObject(line, MethodInfo.class);
                Method method = serviceImpl.getClass().getMethod(methodInfo.getMethodName(), methodInfo.getParams().stream().map(Object::getClass).toArray(Class[]::new));

                Object returnValue = method.invoke(serviceImpl, methodInfo.params.toArray());
                socket.getOutputStream().write((JSON.toJSONString(returnValue) + "\n").getBytes());
                socket.getOutputStream().flush();
            } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }

        }

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

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

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