RPC原理(1)

来源:互联网 发布:手机淘宝店铺怎么收藏 编辑:程序博客网 时间:2024/06/02 06:03

RPC简介

RPC就是远程过程调用,RPC有五个主要的参与者,客户端,本地存根,服务端存根,服务端,通信模型。

一个简单的rpc调用

RpcService rpcService;//远程服务对象String response = rpcService.hello("hi, world");

简单的RPC的基本流程如下图
这里写图片描述

java的RPC的技术简介

动态代理,序列化与反序列化,网络通信框架

动态代理

我们可以按照上图中类似的方式进行RPC通信,但是直接按照上面的流程做,太复杂了,如何简化这个流程,让RPC的使用变得简单起来,这个时候要将公用的东西提取出来变成框架,其中在JAVA中的很重要的技术就是动态地理。动态代理的技术有很多种大致上有jdk的动态代理,cglib的动态代理等,以cglib的动态代理为例进行简单的介绍

public interface MethodInterceptorextends Callback{    /**     * All generated proxied methods call this method instead of the original method.     * The original method may either be invoked by normal reflection using the Method object,     * or by using the MethodProxy (faster).     * @param obj "this", the enhanced object     * @param method intercepted Method     * @param args argument array; primitive types are wrapped     * @param proxy used to invoke super (non-intercepted method); may be called     * as many times as needed     * @throws Throwable any exception may be thrown; if so, super method will not be invoked     * @return any value compatible with the signature of the proxied method. Method returning void will ignore this value.     * @see MethodProxy     */        public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args,                               MethodProxy proxy) throws Throwable;}public class CglibReferenceProxy implements MethodInterceptor {    private Logger logger = LoggerFactory.getLogger(CglibReferenceProxy.class);    public CglibReferenceProxy() {    }    public Object createProxy(Class target) {        Enhancer enhancer = new Enhancer();        enhancer.setSuperclass(target);// 设置代理目标        enhancer.setCallback(this);// 设置回调        enhancer.setClassLoader(target.getClass().getClassLoader());        return enhancer.create();    }    /**     * 在代理实例上处理方法调用并返回结果     *     * @param proxy     *            代理类     * @param method     *            被代理的方法     * @param params     *            该方法的参数数组     * @param methodProxy     */    public Object intercept(Object proxy, Method method, Object[] params,                            MethodProxy methodProxy) throws Throwable {        //在此处进行        //do before        Object result = method.invoke(proxy, params);       // 调用原始对象的方法        //do after        return null;    }}Object targetProxy = (T) cglibReferenceProxy.createProxy(targetInterface);  //targetInterface为想要代理的对象

使用cglib代理需要实现MethodInterceptor接口,然后在intercept写入你想要的逻辑就可以。
动态代理为类提供了增强,可以无中生有,将一个空白的接口生成一个简单的实现是小菜一碟。

0 0