欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单的RPC框架的实现

程序员文章站 2022-06-15 13:53:55
...

一、关于RPC框架的理解

所谓的RPC框架,实质上就是要实现远程服务的调用,而调用的过程是透明的,开发者不用区分是本地调用还是远程调用。

其实,实现一个最简单的rpc框架非常的容易:

1、服务端启动,等待请求。当有请求过来时,通过反射执行方法,将结果对象发送给客户端。

2、客户端通过动态代理对象向服务端发送请求,得到服务端反馈的对象。

二、实现一个最简单的RPC框架

1、定义接口:

public interface HelloService {
    String sayHello(String name);
}

2、定义实现类:

public class HelloServiceImpl implements HelloService {
    @Override
    public String sayHello(String name) {
        return "hello " + name;
    }
}

3、服务的发布和导入:

public class RpcFramework {

    public static void export(final Object service, int port) throws IOException {
        System.out.println("export service " + service.getClass().getName() + " on " + port);
        ServerSocket server = new ServerSocket(port);
        while (true) {
            final Socket socket = server.accept();
            ObjectInputStream input = null;
            ObjectOutputStream output = null;
            try {
                input = new ObjectInputStream(socket.getInputStream());
                String methodName = input.readUTF();
                Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
                Object[] paramValue = (Object[]) input.readObject();
                Method method = service.getClass().getMethod(methodName, parameterTypes);
                Object result = method.invoke(service, paramValue);
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeObject(result);
            } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
                    | NoSuchMethodException | SecurityException | IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    output.close();
                    input.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T reference(final Class<T> interfaceClass, final String host, final int port) throws Exception {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] { interfaceClass }, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket(host, port);
                ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                output.writeUTF(method.getName());
                output.writeObject(method.getParameterTypes());
                output.writeObject(args);
                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                return input.readObject();
            }
        });
    }
}

4、服务端和客户端测试:

public class Server {
    
    public static void main(String[] args) throws Exception {
        HelloService helloService = new HelloServiceImpl();
        RpcFramework.export(helloService, 8000);
    }
}

public class Client {

    public static void main(String[] args) throws Exception {
        HelloService helloService = RpcFramework.reference(HelloService.class, "localhost", 8000);
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            System.out.println(helloService.sayHello("world-" + i));
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

转载于:https://my.oschina.net/solidwang/blog/796940