RPC框架简单原理

来源:互联网 发布:js修改div高度 编辑:程序博客网 时间:2024/06/01 08:43

RPC框架简单原理

一起写RPC框架(一)RPC之我所见 这篇博客对于RPC框架解释的非常的详细
主要参考Dubbo源码的作者梁飞的几句代码实现RPC
对于远程模块的方法的调用,通过代理模式是实现,首先要通过网络请求发送给处理中心,我请求的类信息,调用的方法的名称,调用的参数类型,调用的参数等等,然后将调用Real的服务类的方法返回结果。
远程方法和本地方法实现相同的接口信息,本地方法通过动态代理生成一个代理对象,在实际调用的时候,通过调用代理对象方法,动态代理处理网络请求,将当前调用的类的信息、请求方法的信息、请求的参数等等通过网络请求发送给服务中心,服务中心查找实际处理人,调用真实的方法,然后通过网络返回结果。

简单的服务中心,提供了某个Service服务的暴露

这里没有处理寻找服务的实例的过程,直接将服务的实例保存起来,直接去寻找这个类的方法。
这里的网络请求是简单的模拟一下。

服务中心引用服务,通过Service服务实现的接口的信息进行动态生成一个代理的实例

然后正在的调用接口的实例的时候去调用网络请求将相应的信息传递过去,然后进行处理。

package test;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;/** * descrption: 简单的服务中心 * authohr: wangji * date: 2017-10-17 15:49 */public class RpcFramework {    /**     * 暴露服务     *     * @param service 服务实现     * @param port    服务端口     * @throws Exception     */    public static void export(final Object service, int port) throws Exception {        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);        for (; ; ) {            try {                final Socket socket = server.accept();                new Thread(new Runnable() {                    public void run() {                        try {                            try {                                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();                        }                    }                }).start();            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 引用服务     *     * @param <T>            接口泛型     * @param interfaceClass 接口类型     * @param host           服务器主机名     * @param port           服务器端口     * @return 远程服务     * @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);        //通过动态代理生成当前的接口的一个代理对象的信息        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 {                    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();                }            }        });    }}

首先暴露服务

public interface HelloService {    String hello(String name);}public class HelloServiceImpl implements HelloService {    public String hello(String name) {        return "Hello " + name;    }}public class RpcProvider {    public static void main(String[] args) throws Exception {        HelloService service = new HelloServiceImpl();        //Dubbo中服务类和消费者类的接口的包名称一样哦,不然去找实例的时候找不到        //这里就是服务提供者        RpcFramework.export(service, 1234);    }}

服务的消费者

public interface HelloService {    String hello(String name);}public class RpcConsumer {    public static void main(String[] args) throws Exception {        //生成代理类接口的动态代理        HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);        String hello = service.hello("Hello World Java" );    }}
原创粉丝点击