dubbo服务引用三之建立Invoker的代理对象

一、建立Invoker代理

ReferenceConfig#createProxy方法的结尾处,将FailoverClusterInvoker建立DemoService接口的动态代理。java

proxyFactory.getProxy(invoker);

proxyFactory也是一个带有Adaptive注解方法的SPI类。默认实现JavassistProxyFactory。框架

@SPI("javassist")
public interface ProxyFactory {

    /**
     * create proxy.
     *
     * @param invoker
     * @return proxy
     */
    @Adaptive({Constants.PROXY_KEY})
    <T> T getProxy(Invoker<T> invoker) throws RpcException;

    /**
     * create invoker.
     *
     * @param <T>
     * @param proxy
     * @param type
     * @param url
     * @return invoker
     */
    @Adaptive({Constants.PROXY_KEY})
    <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException;

}

在JavassistProxyFactory#getProxy中
图6
这个地方生成代理的方法很是相似Java的原生的动态代理java.lang.reflect.Proxy,你们感兴趣的能够本身去看一下,这个地方暂不继续写下去了。
咱们主要看一下InvokerInvocationHandler。
这样在执行接口的方法时,将方法名与入参构形成一个RpcInvocation做为入参,传递到Invoker的invoke函数中去。函数

public class InvokerInvocationHandler implements InvocationHandler {

    private final Invoker<?> invoker;

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

    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]);
        }
        return invoker.invoke(new RpcInvocation(method, args)).recreate();
    }

}

二、总结

咱们都说,使用RPC框架时,调用外部服务就像调用本地服务同样方便,那么如何实现服务接口的注入的呢?本文真是从这个角度出发,讲解了dubbo服务引用时,是怎么注入接口的,并讲解了dubbo是经过Invoker调用外部服务的。this

相关文章
相关标签/搜索