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. 【Linux】- apt-get命令

    apt-get,是一条linux命令,适用于deb包管理式的操作系统,主要用于自动从互联网的软件仓库中搜索.安装.升级.卸载软件或操作系统. Advanced Package Tool,又名apt-g ...

  2. 【log4net】- 非常完善的Log4net详细说明

    1.概述 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.本文主要是介绍如何在Visual S ...

  3. 微信支付java

    直接上代码: 1.支付配置PayCommonUtil import com.legendshop.payment.tenpay.util.MD5Util; import com.legendshop. ...

  4. centos7编译安装redis遇坑

    编译redis时:make cc Command not found 原因分析:没有安装gcc,执行: yum install gcc 编译redis时:error: jemalloc/jemallo ...

  5. VisualVM使用方法

    VisualVM 简介 VisualVM 是一个工具,它提供了一个可视界面,用于查看 Java 虚拟机 (Java Virtual Machine, JVM) 上运行的基于 Java 技术的应用程序( ...

  6. android四大组件(一)Activity

    一.创建一个新的Activity 1.android的四大组件都要在清单文件里面配置 2.如果想让你的应用有多个启动图标,你的activity需要这样配置 <intent-filter> ...

  7. 【bzoj2834】回家的路 分层图最短路

    题目描述 输入 输出 样例输入 2 1 1 2 1 1 2 2 样例输出 5 题解 分层图最短路 dis[i][0]表示到i为横向时起点到i的最短路,dis[i][1]表示到i为纵向时起点到i的最短路 ...

  8. C# 面向对象——多态

    多态分三种:1.虚方法 2.抽象类 3.接口 1.虚方法1.将父类的方法标记为虚方法 ,使用关键字 virtual,这个函数可以被子类重新写一个遍. 如: class Program { static ...

  9. BZOJ3675 & 洛谷3648 & UOJ104:[Apio2014]序列分割——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=3675 https://www.luogu.org/problemnew/show/P3648 ht ...

  10. 数据库sharding,横向扩展

    学习资料如下: http://www.cnblogs.com/skyme/p/3459765.html http://my.oschina.net/anthonyyau/blog/307165 htt ...