基於Socket實現簡單RPC框架

廢話不多說,直接上代碼:

1. RpcServer:rpc服務端,用於啓動Socket監聽端口

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RpcServer {

    // 監聽端口
    private int port = 8888;
    // 自定義線程池,用於處理客戶端請求
    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 3000L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));

    // 模擬spring 注入Bean容器
    static Map<String, Object> beanContainer = new HashMap<>();
    static {
        beanContainer.put("helloService", new HelloServiceImpl());
    }

    public void start() {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true) {
            try {
                System.out.println("服務端啓動成功,等待請求。。。");
                Socket s = ss.accept();
                threadPool.submit(new RpcServerHandler(s));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2. RpcServerHandler:處理客戶端請求

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class RpcServerHandler implements Runnable{

    Socket s;

    public RpcServerHandler(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        System.out.println("服務端開始處理請求");
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            ois = new ObjectInputStream(s.getInputStream());
            // 獲取接口名稱
            String serviceName = ois.readUTF();
            // 獲取目標方法名
            String methodName = ois.readUTF();
            // 具體的實現類beanName
            String beanName = ois.readUTF();
            // 使用反射調用目標方法
            Class<?> c = Class.forName(serviceName);
            Method m = c.getMethod(methodName);
            Object result = m.invoke(RpcServer.beanContainer.get(beanName));
            oos = new ObjectOutputStream(s.getOutputStream());
            // 方法返回值返回客戶端
            oos.writeObject(result);
            System.out.println("服務端處理請求成功");
        } catch (Exception e) {
            System.out.println("RpcHandler error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            if(null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != oos) {
                try {
                    oos.flush();
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. RpcClientProxy: 客戶端接口代理類

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class RpcClientProxy {
    // 服務端IP
    private final static String ipAddress = "localhost";
    // 服務端端口
    private final static int port = 4444;

    /* 創建代理對象,在代理對象中使用Socket請求服務端獲取數據 */
    public static Object proxy(Class interfaces, String beanName) {
        return Proxy.newProxyInstance(RpcClientProxy.class.getClassLoader(), new Class[]{interfaces}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                ObjectInputStream ois = null;
                ObjectOutputStream oos = null;
                try {
                    System.out.println("客戶端開始請求數據");
                    Socket s = new Socket(ipAddress, port);
                    oos = new ObjectOutputStream(s.getOutputStream());
                    oos.writeUTF(interfaces.getName());
                    oos.writeUTF(method.getName());
                    oos.writeUTF(beanName);
                    oos.flush();
                    ois = new ObjectInputStream(s.getInputStream());
                    Object obj = ois.readObject();
                    return obj;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if(null != ois) {
                        try {
                            ois.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(null != oos) {
                        try {
                            oos.flush();
                            oos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }
        });
    }
}

4. HelloService : 測試接口類

public interface HelloService {

    String hello();
}

5. HelloServiceImpl: 測試接口實現類

public class HelloServiceImpl implements HelloService {

    @Override
    public String hello() {
        System.out.println("RpcServer return hello world");
        return "hello world";
    }
}

6. RpcClient 測試類

public class RpcClient {

    public static void main(String[] args) {
        RpcServer rpcServer = new RpcServer();
        // 異步啓動服務端
        new Thread(new Runnable() {
            @Override
            public void run() {
                rpcServer.start();
            }
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("開始啓動rpc客戶端");

        // 模擬客戶端調用接口
        for(int i = 0; i < 2; i++) {
            HelloService helloService = (HelloService) RpcClientProxy.proxy(HelloService.class, "helloService");
            String s = helloService.hello();
            System.out.println(s);
        }
    }
}

 

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