springCloud中最重要的就是微服务之间的调用,因为网络延迟或者调用超时会直接导致程序异常,因此超时的配置及处理就至关重要。

在开发过程中被调用的微服务打断点发现会又多次重试的情况,测试环境有的请求响应时间过长也会出现多次请求,网上查询了配置试了一下无果,决定自己看看源码。
本人使用的SpringCloud版本是Camden.SR3。

微服务间调用其实走的是http请求,debug了一下默认的ReadTimeout时间为5s,ConnectTimeout时间为2s,我使用的是Fegin进行微服务间调用,底层用的还是Ribbon,网上提到的配置如下

ribbon:
ReadTimeout:
ConnectTimeout:
MaxAutoRetries:
MaxAutoRetriesNextServer:

超时时间是有效的但是重试的次数无效,如果直接使用ribbon应该是有效的。

下面开始测试:
在微服务B中建立测试方法,sleep 8s 确保请求超时

@PostMapping("/testa")
public Integer testee(){
try {
Thread.sleep(8000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return ;
}
 

在微服务A中使用fegin调用此方法时看到有异常

看到在SynchronousMethodHandler中请求的方法

Object executeAndDecode(RequestTemplate template) throws Throwable {
Request request = targetRequest(template);
if (logLevel != Logger.Level.NONE) {
logger.logRequest(metadata.configKey(), logLevel, request);
}
Response response;
long start = System.nanoTime();
try {
response = client.execute(request, options);
response.toBuilder().request(request).build();
} catch (IOException e) {
if (logLevel != Logger.Level.NONE) {
logger.logIOException(metadata.configKey(), logLevel, e, elapsedTime(start));
}
//出现异常后抛出RetryableException
throw errorExecuting(request, e);
}

出现异常后调用 throw errorExecuting(request, e) 抛出异常

在调用executeAndDecode的地方catch

@Override
public Object invoke(Object[] argv) throws Throwable {
RequestTemplate template = buildTemplateFromArgs.create(argv);
Retryer retryer = this.retryer.clone();
while (true) {
try {
return executeAndDecode(template);
} catch (RetryableException e) {
//重试的地方
retryer.continueOrPropagate(e);
if (logLevel != Logger.Level.NONE) {
logger.logRetry(metadata.configKey(), logLevel);
}
continue;
}
}
}

retryer.continueOrPropagate(e); 这句就是关键继续跟进

public void continueOrPropagate(RetryableException e) {
//maxAttempts是构造方法传进来的大于重试次数抛出异常,否则继续循环执行请求
if (attempt++ >= maxAttempts) {
throw e;
}

默认的Retryer构造器

public Default() {
this(, SECONDS.toMillis(), );
}

第一个参数period是请求重试的间隔算法参数,第二个参数maxPeriod 是请求间隔最大时间,第三个参数是重试的次数。算法如下:

long nextMaxInterval() {
long interval = (long) (period * Math.pow(1.5, attempt - ));
return interval > maxPeriod ? maxPeriod : interval;
}

新建一个配置类

@Configuration
public class FeginConfig {
@Bean
public Retryer feginRetryer(){
Retryer retryer = new Retryer.Default(, SECONDS.toMillis(), );
return retryer;
}
}
在feginClient是加入configuration的配置
@FeignClient(value = "fund-server",fallback = FundClientHystrix.class,configuration = FeginConfig.class)
public interface FundClient

重启重试,只调用了一次,Fegin重试次数解决。
我们再看看请求超时这里的参数

@Override
public Response execute(Request request, Request.Options options) throws IOException {
try {
URI asUri = URI.create(request.url());
String clientName = asUri.getHost();
URI uriWithoutHost = cleanUrl(request.url(), clientName);
FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
this.delegate, request, uriWithoutHost);
//请求参数
IClientConfig requestConfig = getClientConfig(options, clientName);
return lbClient(clientName).executeWithLoadBalancer(ribbonRequest,
requestConfig).toResponse();
}
catch (ClientException e) {
IOException io = findIOException(e);
if (io != null) {
throw io;
}
throw new RuntimeException(e);
}
}

其中ReadTimeout 和 ConnectTimeout 读取的就是ribbon的配置,再来看一眼

ribbon:
ReadTimeout:
ConnectTimeout:
MaxAutoRetries:
MaxAutoRetriesNextServer:

如果想覆盖ribbon的超时设置可以在刚刚写的FeginConfig里注入下面的bean

@Bean
public Request.Options feginOption(){
Request.Options option = new Request.Options(,);
return option;
}

总结:使用开源的东西在弄不清问题出在哪时最好能看看源码,对原理的实现以及自己的编码思路都有很大的提升。

http://www.jianshu.com/p/767f3c72b547

SpringCloud Fegin超时重试源码的更多相关文章

  1. 【springcloud】2.eureka源码分析之令牌桶-限流算法

    国际惯例原理图 代码实现 package Thread; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomi ...

  2. SpringCloud之RefreshScope 源码解读

    SpringCloud之RefreshScope @Scope 源码解读 Scope(org.springframework.beans.factory.config.Scope)是Spring 2. ...

  3. Flask框架 (四)—— 请求上下文源码分析、g对象、第三方插件(flask_session、flask_script、wtforms)、信号

    Flask框架 (四)—— 请求上下文源码分析.g对象.第三方插件(flask_session.flask_script.wtforms).信号 目录 请求上下文源码分析.g对象.第三方插件(flas ...

  4. SpringCloud升级之路2020.0.x版-33. 实现重试、断路器以及线程隔离源码

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 在前面两节,我们梳理了实现 Feign 断路器以及线程隔离的思路,并说明了如何优化目前的负 ...

  5. SpringCloud Feign 之 超时重试次数探究

    SpringCloud Feign 之 超时重试次数探究 上篇文章,我们对Feign的fallback有一个初步的体验,在这里我们回顾一下,Fallback主要是用来解决依赖的服务不可用或者调用服务失 ...

  6. SpringCloud 源码系列(1)—— 注册中心 Eureka(上)

    Eureka 是 Netflix 公司开源的一个服务注册与发现的组件,和其他 Netflix 公司的服务组件(例如负载均衡.熔断器.网关等)一起,被 Spring Cloud 整合为 Spring C ...

  7. SpringCloud 源码系列(4)—— 负载均衡 Ribbon

    一.负载均衡 1.RestTemplate 在研究 eureka 源码上篇中,我们在 demo-consumer 消费者服务中定义了用 @LoadBalanced 标记的 RestTemplate,然 ...

  8. SpringCloud 源码系列(5)—— 负载均衡 Ribbon(下)

    SpringCloud 源码系列(4)-- 负载均衡 Ribbon(上) SpringCloud 源码系列(5)-- 负载均衡 Ribbon(下) 五.Ribbon 核心接口 前面已经了解到 Ribb ...

  9. SpringCloud 源码系列(6)—— 声明式服务调用 Feign

    SpringCloud 源码系列(1)-- 注册中心 Eureka(上) SpringCloud 源码系列(2)-- 注册中心 Eureka(中) SpringCloud 源码系列(3)-- 注册中心 ...

随机推荐

  1. Perfmon - Windows 自带系统监控工具

    一. 简述 可以用于监视CPU使用率.内存使用率.硬盘读写速度.网络速度等. Perfmon提供了图表化的系统性能实时监视器.性能日志和警报管理,系统的性能日志可定义为二进制文件.文本文件.SQLSE ...

  2. 委托,事件,lambda表达式

    开篇说明三个点: 委托是一种类型 事件是委托的实例 lambda表达式是一个方法(匿名方法) [未完待续]

  3. 钉钉 E应用 打开分享外链

    钉钉 E应用 打开分享外链 外部链接 https://open-doc.dingtalk.com/microapp/dev https://open-doc.dingtalk.com/microapp ...

  4. Linux命令发送Http GET/POST请求

    Get请求 curl命令模拟Get请求: 1.使用curl命令: curl "http://www.baidu.com" 如果这里的URL指向的是一个文件或者一幅图都可以直接下载到 ...

  5. 限制玻尔兹曼机(Restricted Boltzmann Machine)RBM

    假设有一个二部图,每一层的节点之间没有连接,一层是可视层,即输入数据是(v),一层是隐藏层(h),如果假设所有的节点都是随机二值变量节点(只能取0或者1值)同时假设全概率分布满足Boltzmann 分 ...

  6. OpenStack Queens版本Horizon定制化开发

    工具环境 1.VMware workstation 12+: 2.Ubuntu系统+Linux Pycharm: 3.OpenStack Queens版本Horizon代码: 问题及解决 1.项目代码 ...

  7. Luogu1053 NOIP2005篝火晚会

    首先造出所要求的得到的环.如果将位置一一对应上,答案就是不在所要求位置的人数.因为显然这是个下界,并且脑补一下能构造出方案达到这个下界. 剩下的问题是找到一种对应方案使错位数最少.可以暴力旋转这个环, ...

  8. python中深copy,浅copy

    版权声明:本文为博主原创文章,未经博主允许不得转载. >>> mylist1 = [1, 2, 3, 4] >>> myl = mylist1 >>&g ...

  9. c# 日志记录 行号

    Console.WriteLine(ex.Message); //通过如下代码来记录异常详细的信息 ); Console.WriteLine("文件名:{0},行号:{1},列号:{2}&q ...

  10. [bzoj] 1588 营业额统计 || Splay板子题

    原题 给出一个n个数的数列ai ,对于第i个元素ai定义\(fi=min(|ai-aj|) (1<=j<i)\),f1=a1,求\(/sumfi\) Splay板子题. Splay讲解:h ...