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

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

private T createProxy(Map 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 getProxy(Invoker 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();
    }
}

你可能感兴趣的:(dubbo技术内幕九 ReferenceBean 的代理过程)