dubbo技术内幕九 ReferenceBean 的代理过程

经过前几章的讲解,相信大家对dubbo有了个大概的了解,让我们再回到最开始,在ReferenceConfig类的方法里面如下

private T createProxy(Map<String, String> map) {

//最后一句
return (T) proxyFactory.getProxy(invoker);

}

其中T是我们定义的暴露给消费者的Interface,通过动态代理,将我们的invoker转化成了Interface,动态代理在这里的动作是将对Interface的方法的调用代理给invoker进行调用,我们现在看下其是怎么实现的。
由于proxyFactory的默认实现是JavassistProxyFactory,代码如下

Class  JavassistProxyFactory
public class JavassistProxyFactory extends AbstractProxyFactory {

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
        return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
    }

上面可以看到针对invoker针对InvokerInvocationHandler对其进行了封装,源码如下

public class InvokerInvocationHandler implements InvocationHandler {
   //内部代理的invoker
    private final Invoker<?> invoker;

    public InvokerInvocationHandler(Invoker<?> handler) {
        this.invoker = handler;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(invoker, args);
        }
        if ("toString".equals(methodName) && parameterTypes.length == 0) {
            return invoker.toString();
        }
        if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
            return invoker.hashCode();
        }
        if ("equals".equals(methodName) && parameterTypes.length == 1) {
            return invoker.equals(args[0]);
        }
        //将method封装成一个RpcInvocation传给invoker进行invoke
        return invoker.invoke(new RpcInvocation(method, args)).recreate();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容