dubbo的超时重试
dubbo的超时分为服务端超时 SERVER_TIMEOUT 和客户端超时 CLIENT_TIMEOUT。本文讨论服务端超时的情形:
超时:consumer发送调用请求后,等待服务端的响应,若超过timeout时间仍未收到响应,则抛异常。
dubbo consumer 超时重试的逻辑在 FailoverClusterInvoker.doInvoke 中:
public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers,
LoadBalance loadbalance) throws RpcException {
List<Invoker<T>> copyinvokers = invokers;
checkInvokers(copyinvokers, invocation);
//取retries参数值,默认值为2,所以len默认为3
int len = getUrl().getMethodParameter(invocation.getMethodName(), Constants.RETRIES_KEY,
Constants.DEFAULT_RETRIES) + 1;
if (len <= 0) {
len = 1;
}
// retry loop.
RpcException le = null; // last exception.
List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size()); // invoked invokers.
Set<String> providers = new HashSet<String>(len);
for (int i = 0; i < len; i++) {
//重试时,进行重新选择,避免重试时invoker列表已发生变化.
//注意:如果列表发生了变化,那么invoked判断会失效,因为invoker示例已经改变
if (i > 0) {
checkWheatherDestoried();
copyinvokers = list(invocation);
//重新检查一下
checkInvokers(copyinvokers, invocation);
}
Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
invoked.add(invoker);
RpcContext.getContext().setInvokers((List)invoked);
try {
//继续invoker链的调用
Result result = invoker.invoke(invocation);
if (le != null && logger.isWarnEnabled()) {
//打印日志:上次调用产生的异常
logger.warn("Although retry the method XXX");
}
//调用成功,即返回。如果产生RpcException异常,进入catch块,设置le。
return result;
} catch (RpcException e) {
//在DubboInvoker.doInvoke中会把TimeoutException封装成RpcException
//所以超时异常会进入这个catch分支,开始for循环的下一次调用
if (e.isBiz()) { // biz exception.
throw e;
}
le = e;
} catch (Throwable e) {
le = new RpcException(e.getMessage(), e);
} finally {
providers.add(invoker.getUrl().getAddress());
}
} // retry loop.
//调用len次后,仍然没有结果,则抛异常。
throw new RpcException(le != null ? le.getCode() : 0, "Failed to invoke the method "
+ invocation.getMethodName() + " in the service " + getInterface().getName()
+ ". Tried " + len + " times of the providers " + providers
+ " (" + providers.size() + "/" + copyinvokers.size()
+ ") from the registry " + directory.getUrl().getAddress()
+ " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
+ Version.getVersion() + ". Last error is: "
+ (le != null ? le.getMessage() : ""), le != null && le.getCause() != null ? le.getCause() : le);
}
当invoker的调用链进行到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) {
//oneway的意思是:consumer不需要调用结果。需要配置return="false"
boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false);
currentClient.send(inv, isSent);
RpcContext.getContext().setFuture(null);
return new RpcResult();
} else if (isAsync) {
//如果consumer需要调用结果,但又不想阻塞程序,则设置return="true", async="true"
ResponseFuture future = currentClient.request(inv, timeout);
//在RpcContext中设置Future,返回空的RpcResult
RpcContext.getContext().setFuture(new FutureAdapter<Object>(future));
return new RpcResult();
} else {
//如果consumer想阻塞获取provider的调用结果,不需要做配置,默认即可。
RpcContext.getContext().setFuture(null);
//currentClient.request会发送请求,返回Future。调用Future.get导致阻塞
return (Result) currentClient.request(inv, timeout).get();
}
} catch (TimeoutException e) {
//调用超时,将TimeoutException封装成RpcException。
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);
}
}
currentClient.request(inv, timeout).get(); 会阻塞等待响应,超时则会抛出异常。
// HeaderExchangeChannel.request
public ResponseFuture request(Object request, int timeout) throws RemotingException {
if (closed) {
throw new RemotingException(this.getLocalAddress(), null,
"Failed to send request " + request + ", cause: The channel " + this + " is closed!");
}
// create request.
Request req = new Request();
req.setVersion("2.0.0");
req.setTwoWay(true);
req.setData(request);
//设置超时
DefaultFuture future = new DefaultFuture(channel, req, timeout);
try{
channel.send(req);
}catch (RemotingException e) {
future.cancel();
throw e;
}
return future;
} // DefaultFuture.get(int timeout)
public Object get(int timeout) throws RemotingException {
if (timeout <= 0) {
timeout = Constants.DEFAULT_TIMEOUT;
}
if (! isDone()) {
//记录开始时间
long start = System.currentTimeMillis();
lock.lock();
try {
while (! isDone()) {
//(1)await超时醒来,但是未收到响应:则isDone为false,但是System.currentTimeMillis() - start > timeout 为true
//(2)provider及时响应。更具体的说法是等待DubboClientHandler线程接收响应后,唤醒该线程。isDone会设置为true
//(3)RemotingInvocationTimeoutScan线程扫描到超时,然后创建一个超时响应,并唤醒这个等待。isDone被设置为true
done.await(timeout, TimeUnit.MILLISECONDS);
if (isDone() || System.currentTimeMillis() - start > timeout) {
break;
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
if (! isDone()) {
//抛出超时异常
throw new TimeoutException(sent > 0, channel, getTimeoutMessage(false));
}
}
return returnFromResponse();
}
在DefaultFuture类中有一个内部类RemotingInvocationTimeoutScan,负责扫描超时的调用,在客户端构造超时响应。
private static class RemotingInvocationTimeoutScan implements Runnable { public void run() {
while (true) {
try {
for (DefaultFuture future : FUTURES.values()) {
if (future == null || future.isDone()) {
continue;
}
if (System.currentTimeMillis() - future.getStartTimestamp() > future.getTimeout()) {
// create exception response.
Response timeoutResponse = new Response(future.getId());
// set timeout status.
timeoutResponse.setStatus(future.isSent() ? Response.SERVER_TIMEOUT : Response.CLIENT_TIMEOUT);
timeoutResponse.setErrorMessage(future.getTimeoutMessage(true));
// handle response.
DefaultFuture.received(future.getChannel(), timeoutResponse);
}
}
Thread.sleep(30);
} catch (Throwable e) {
logger.error("Exception when scan the timeout invocation of remoting.", e);
}
}
}
} static {
Thread th = new Thread(new RemotingInvocationTimeoutScan(), "DubboResponseTimeoutScanTimer");
th.setDaemon(true);
th.start();
}
dubbo的超时重试的更多相关文章
- Dubbo超时重试机制带来的数据重复问题
Dubbo的超时重试机制为服务容错.服务稳定提供了比较好的框架支持,但是在一些比较特殊的网络环境下(网络传输慢,并发多)可能 由于服务响应慢,Dubbo自身的超时重试机制(服务端的处理时间超过了设定的 ...
- dobbo 服务配置详解(解决超时重试问题)
<!-- reference method --> <dubbo:reference interface="com.xx.XxxService"> ...
- dubbo超时重试和异常处理
dubbo超时重试和异常处理 dubbo超时重试和异常处理 参考: https://www.cnblogs.com/ASPNET2008/p/7292472.html https://www.tuic ...
- 5.如何基于 dubbo 进行服务治理、服务降级、失败重试以及超时重试?
作者:中华石杉 面试题 如何基于 dubbo 进行服务治理.服务降级.失败重试以及超时重试? 面试官心理分析 服务治理,这个问题如果问你,其实就是看看你有没有服务治理的思想,因为这个是做过复杂微服务的 ...
- 面试系列26 如何基于dubbo进行服务治理、服务降级、失败重试以及超时重试
(1)服务治理 1)调用链路自动生成 一个大型的分布式系统,或者说是用现在流行的微服务架构来说吧,分布式系统由大量的服务组成.那么这些服务之间互相是如何调用的?调用链路是啥?说实话,几乎到后面没人搞的 ...
- Volley超时重试机制
基础用法 Volley为开发者提供了可配置的超时重试机制,我们在使用时只需要为我们的Request设置自定义的RetryPolicy即可. 参考设置代码如下: int DEFAULT_TIMEOUT_ ...
- 超时重试(一)ajax
我们使用jquery的ajax,超时重试可以采用两种方式,一种是配置ajax的timeout的参数,另一种就是以setTimeout定时器的方式实现: 1)timeout参数配置方式 var xhr ...
- SpringCloud Feign 之 超时重试次数探究
SpringCloud Feign 之 超时重试次数探究 上篇文章,我们对Feign的fallback有一个初步的体验,在这里我们回顾一下,Fallback主要是用来解决依赖的服务不可用或者调用服务失 ...
- 使用 Polly 实现复杂策略(超时重试)
一.背景 第一次接触 Polly 还是在做某个微服务系统的时候,那时只会使用单一的超时策略与重试策略,更加高级的特性就没有再进行学习了.最近开为某个客户开发 PC 端的上位机的时候,客户有个需求,在发 ...
随机推荐
- django 加载静态文件(图片,js,css)
昨天写过一个项目通过django上传展示图片,但是今天写项目的时候发现出现了问题,静态文件加载不出来了,尴尬的一笔~ 记录一下静态文件的使用方法,基础~ ----------------------- ...
- C_Learning(3)
/ 结构体 / 声明结构体类型的一般形式: struct 结构体名[--表示的是这个结构体的类型] { 成员列表 }; [不要漏掉这个";"] / 声明结构可以放在main函 ...
- [算法整理]树上求LCA算法合集
1#树上倍增 以前写的博客:http://www.cnblogs.com/yyf0309/p/5972701.html 预处理时间复杂度O(nlog2n),查询O(log2n),也不算难写. 2#st ...
- Timer,TimerTask,Handler
新建一个定时器线程,通过此线程每一秒发送数据到Handler,然后通过Handler来修改UI. 1.获得Handler,Timer,TimerTask对象. Handler handler=new ...
- CSS高级布局
float属性 基本浮动规则 先来了解一下block元素和inline元素在文档流中的排列方式. block元素通常被现实为独立的一块,独占一行,多个block元素会各自新起一行,默认block元素宽 ...
- The DELETE statement conflicted with the REFERENCE constraint
Page是主表,主键是pageid:UserGroupPage表中的PageID字段是Page表里的数据. https://www.codeproject.com/Questions/677277/I ...
- leetcode 最长有效括号
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度. 示例 1: 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()&quo ...
- OpFlex
参考: OpFlex Main OpFlex: Building and Running OpFlex Building mkdir -p ~/work pushd work git clone ht ...
- Mac OSX 安装qemu
参考: Installing QEMU on OS X Homebrew Mac OSX 安装qemu 1.Install Homebrew: /usr/bin/ruby -e "$(cur ...
- 关于C++中的友元函数的总结
1.友元函数的简单介绍 1.1为什么要使用友元函数 在实现类之间数据共享时,减少系统开销,提高效率.如果类A中的函数要访问类B中的成员(例如:智能指针类的实现),那么类A中该函数要是类B的友元函数.具 ...