/** * RPC监听和远程方法调用 * @param service RPC远程方法调用的接口实例 * @param port 监听的端口 * @throws Exception

    ServerSocket serverSocket = new ServerSocket(port);
    while (true) {
        //开始接收客户端的消息,并以此创建套接字
        final Socket socket = serverSocket.accept();
        //多线程执行,这里的问题是连接数过大,线程池的线程数会耗尽
        executorService.execute(() -> {
            try {
                //创建呢一个对内传输的对象流,并绑定套接字
                try {
                        //从对象流中读取接口方法的方法名
                        String methodName = input.readUTF();
                        //从对象流中读取接口方法的所有参数
                        Object[] args = (Object[]) input.readObject();
                        Class[] argsTypes = new Class[args.length];
                        for (int i = 0;i < args.length;i++) {
                            argsTypes[i] = args[i].getClass();
1
2

}
                        //创建一个对外传输的对象流,并绑定套接字
                        //这里是为了将反射执行结果传递回消费者端
                        try {
                            Class<?>[] interfaces = service.getClass().getInterfaces();
                            Method method = null;
                            for (int i = 0;i < interfaces.length;i++) {
                                method = interfaces[i].getDeclaredMethod(methodName,argsTypes);
                                if (method != null) {
                                    break;
1
}
                            Object result = method.invoke(service, args);
                            //将反射执行结果写入对外传输的对象流中
                            output.writeObject(result);
                        } catch (Throwable t) {
                            output.writeObject(t);
1
}
                    } catch (Exception e) {
                        e.printStackTrace();
1
2
3
        }
}
}
        });
1
启动提供者端的网络侦听和远程调用

public class RPCProviderMain {
public static void main(String[] args) throws Exception {
HelloService service = new HelloServiceImpl();
ProviderReflect.provider(service,8083);

1
2
    }
启动消费者的动态代理调用

public class RPCConsumerMain {
public static void main(String[] args) throws InterruptedException {
HelloService service = ConsumerProxy.consume(HelloService.class,”127.0.0.1”,8083);
for (int i = 0;i < 1000;i++) {
String hello = service.sayHello(“你好_” + i);
System.out.println(hello);
Thread.sleep(1000);

1
2
3
4
        }
运行结果
hello,你好_0 hello,你好_1 hello,你好_2 hello,你好_3 hello,你好_4 hello,你好_5
.....

本文标题: 自己实现一个RPC框

发布时间: 2021年01月11日 00:00

最后更新: 2026年09月16日 05:40

原始链接: https://haoxiang.eu.org/2a99d64a/

版权声明: 本文著作权归作者所有,均采用CC BY-NC-SA 4.0许可协议,转载请注明出处!

× 喜欢就赞赏一下呗!
打赏二维码