您的位置:首页 > 其它

dubbo源码解析(十) dubbo服务引用原理

2018-03-20 17:53 531 查看
 dubbo服务引用是通过spring的schema实现的。消费端的配置如下: <dubbo:reference id="demoService" check="false" interface="com.alibaba.dubbo.demo.DemoService"/>进入DubboNamespaceHandler这个类:



按照前几节的介绍,context.getBean("demoService")应该返回一个ReferenceBean对象,但事实上却不是,原因就是因为ReferenceBean实现了FactoryBean接口。
在Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean。FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象。

进入ReferenceBean.getObject()方法:



最终进入ReferenceConfig的createProxy:



这一段代码首先判断是否是本地引用,是否是用户指定的url调用,本例是通过注册中心配置拼装URL:



进入refprotocol.refer(interfaceClass, urls.get(0))方法:
refprotocol是Protocol$Adpative的一个对象:



最终进入RegistryProtocol的refer方法:



进入doRefer:



其中注册的节点名为:dubbo/com.alibaba.dubbo.demo.DemoService/consumers
订阅了
/dubbo/com.alibaba.dubbo.demo.DemoService/providers, /dubbo/com.alibaba.dubbo.demo.DemoService/configurators,/dubbo/com.alibaba.dubbo.demo.DemoService/routers三个节点。
进入registry.subscribe:



最终进入ZookeeperRegistry的doSubscribe方法:



最终进入RegistryDirectory.notify:



refreshInvoker(invokerUrls)作用是刷新缓存中的invoker列表。例如当服务发布者增加机器或者减少机器时会触发该方法:



回到ReferenceConfig的createProxy方法: invoker = cluster.join(new StaticDirectory(u, invokers));这段代码的作用是加入集群路由。
proxyFactory.getProxy(invoker)的作用就是创建服务代理,利用jdk自带的InvocationHandler,创建InvokerInvocationHandler对象。

这个InvokerInvocationHandler对象就是context.getBean("demoService")返回的对象。



进入demoService.sayHello方法,实际上是进入InvokerInvocationHandler.invoke方法: 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();
}进入invoker.invoke,即进入MockClusterInvoker.invoke,表示进入集群: public Result invoke(Invocation invocation) throws RpcException {
Result result = null;

String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim();
if (value.length() == 0 || value.equalsIgnoreCase("false")) {
//no mock
result = this.invoker.invoke(invocation);
} else if (value.startsWith("force")) {
if (logger.isWarnEnabled()) {
logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
}
//force:direct mock
result = doMockInvoke(invocation, null);
} else {
//fail-mock
try {
result = this.invoker.invoke(invocation);
} catch (RpcException e) {
if (e.isBiz()) {
throw e;
} else {
if (logger.isWarnEnabled()) {
logger.info("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
}
result = doMockInvoke(invocation, e);
}
}
}
return result;
}



进入this.invoker.invoke(invocation): public Result invoke(final Invocation invocation) throws RpcException {

checkWhetherDestroyed();

LoadBalance loadbalance;

List<Invoker<T>> invokers = list(invocation);
if (invokers != null && invokers.size() > 0) {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
.getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
} else {
loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
}
RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
return doInvoke(invocation, invokers, loadbalance);
}进入 list(invocation),最终进入AbstractDirectory.list(Invocation invocation): public List<Invoker<T>> list(Invocation invocation) throws RpcException {
if (destroyed) {
throw new RpcException("Directory already destroyed .url: " + getUrl());
}
List<Invoker<T>> invokers = doList(invocation);
List<Router> localRouters = this.routers; // local reference
if (localRouters != null && localRouters.size() > 0) {
for (Router router : localRouters) {
try {
if (router.getUrl() == null || router.getUrl().getParameter(Constants.RUNTIME_KEY, true)) {
invokers = router.route(invokers, getConsumerUrl(), invocation);//进入路由 
}
} catch (Throwable t) {
logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t);
}
}
}
return invokers;
}最终根据路由规则获取到invokers:



回到AbstractClusterInvoker.invoke:



loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
.getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));表示获取负载均衡策略,默认的是取模轮循。
进入doInvoke(invocation, invokers, loadbalance),即:FailoverClusterInvoker.doInvoke:



进入Result result = invoker.invoke(invocation),在经历:1.ProtocolFilterWrapper.invoke
2.ConsumerContextFilter.invoke
3.ProtocolFilterWrapper.invoke
4.MonitorFilter.invoke
5.ProtocolFilterWrapper.invoke
6.FutureFilter.invoke
7.ListenerInvokerWrapper.invoke
8.AbstractInvoker.invoke最终进入DubboInvoker的doInvoke方法: protected Result doInvoke(final Invocation invocation) throws Throwable {
RpcInvocation inv = (RpcInvocation) invocation;
final String methodName = RpcUtils.getMethodName(invocation);
inv.setAttachment(Constants.PATH_KEY, getUrl().getPath());
inv.setAttachment(Constants.VERSION_KEY, version);

ExchangeClient currentClient;
if (clients.length == 1) {
currentClient = clients[0];
} else {
currentClient = clients[index.getAndIncrement() % clients.length];
}
try {
boolean isAsync = RpcUtils.isAsync(getUrl(), invocation);
boolean isOneway = RpcUtils.isOneway(getUrl(), invocation);
int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
if (isOneway) {
boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false);
currentClient.send(inv, isSent);
RpcContext.getContext().setFuture(null);
return new RpcResult();
} else if (isAsync) {
ResponseFuture future = currentClient.request(inv, timeout);
RpcContext.getContext().setFuture(new FutureAdapter<Object>(future));
return new RpcResult();
} else {
RpcContext.getContext().setFuture(null);
return (Result) currentClient.request(inv, timeout).get();
}
} catch (TimeoutException e) {
throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
} catch (RemotingException e) {
throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
}
}进入(Result) currentClient.request(inv, timeout)方法:



最终进入NettyChannel的send方法:public void send(Object message, boolean sent) throws RemotingException {
super.send(message, sent);

boolean success = true;
int timeout = 0;
try {
ChannelFuture future = channel.write(message);
if (sent) {
timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
success = future.await(timeout);
}
Throwable cause = future.getCause();
if (cause != null) {
throw cause;
}
} catch (Throwable e) {
throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e);
}

if (!success) {
throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress()
+ "in timeout(" + timeout + "ms) limit");
}
}channel.write(message)表示通过netty的channel发送网络数据。
通过以上步骤就可以调用远程方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: