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 端的上位机的时候,客户有个需求,在发 ...
随机推荐
- 企业应用开发中最常用c++库
log4cpp,http://log4cpp.sourceforge.net/,跟log4j一样,不说最重要,绝对是最常用的. zk 客户端,https://blog.csdn.net/yangzhe ...
- [noip模拟题]排队
[问题描述] 小sin所在的班有n名同学,正准备排成一列纵队,但他们不想按身高从矮到高排,那样太单调,太没个性.他们希望恰好有k对同学是高的在前,矮的在后,其余都是矮的在前,高的在后.如当n=5,k= ...
- __NSCFConstantString && __NSPlaceholderDictionary
一 -[__NSCFConstantString size]: unrecognized selector sent to instance 0x53ea70 该错误是在我将NSString类型的参数 ...
- MAKEFILE 编程基础之一【转】
本文转载自:http://www.himigame.com/gcc-makefile/766.html 概述: 什么是makefile?或许很多Winodws的程序员都不知道这个东西,因为那些Wind ...
- newcode wyh的吃鸡(优势队列+BFS)题解
思路: 要用优势队列,因为有的+2,有的+1,所以队列中的步长是不单调的,所以找到一个答案但不一定最小,所以用优势队列把小的放在队首. 要记录状态,所以开了三维,题目和昨天做的那道小明差不多 vis开 ...
- HDU1556 Color the ball(差分数组)题解
Color the ball Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) T ...
- 【第三十九章】 微服务CICD(1)- gitlab搭建与使用(docker版)
一.下载docker镜像 前提:docker引擎已经安装好. docker pull gitlab/gitlab-ce gitlab是8.13.1版本. 二.启动应用 docker run -d -h ...
- HDU 6127 Hard challenge(扫描线)
http://acm.hdu.edu.cn/showproblem.php?pid=6127 题意: 有n个点,每个点有一个$(x,y)$坐标和一个权值,任意两点之间都有连线,并且连线的权值为两个顶点 ...
- booststrap select2的应用总结
本身对前端js了解不是特别多,在项目中,遇到很多前端的问题,有时间整理一下,有不对的地方,不吝赐教,多多批评指正. 在项目中,遇到最多的select下拉框情景,莫过于多选和单选了 单选是很容易理解的, ...
- hdu 5651 xiaoxin juju needs help 逆元 两种求解方式
xiaoxin juju needs help Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/ ...