1、创建Invoker代理
ReferenceConfig#createProxy方法的结尾处,将FailoverClusterInvoker创建DemoService接口的动态代理。
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();
}
}
2、总结
我们都说,使用RPC框架时,调用外部服务就像调用本地服务一样方便,那么如何实现服务接口的注入的呢?本文真是从这个角度出发,讲解了dubbo服务引用时,是怎么注入接口的,并讲解了dubbo是通过Invoker调用外部服务的。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。