OpenFeign和Ribbon的过期时间

openfeign之前的版本中集成了ribbon,并且openfeignribbon都有超时时间,那在项目中具体以哪个超时时间为准,我们一探究竟

首先是依赖的版本:

<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-alibaba-dependencies</artifactId>
   <version>2.2.6.RELEASE</version>
   <type>pom</type>
   <scope>import</scope>
</dependency>

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-dependencies</artifactId>
   <version>Hoxton.SR9</version>
   <type>pom</type>
   <scope>import</scope>
</dependency>

在 Provider 中编写一个接口,直接睡眠 3 秒

@GetMapping("/hello")
public String hello() {
  try {
      TimeUnit.SECONDS.sleep(3);
  } catch (InterruptedException e) {
      e.printStackTrace();
  }
  return "provider hello";
}

我们调用 Consumer 项目中的接口,在 Consumer 接口中通过 Feign 接口调用 Provider 的 hello 接口 ,在 Consumer 中直接报 Read time out
在这里插入图片描述
这是因为在ribbon,默认的连接超时和读超时都为 1 秒,在RibbonClientConfiguration类可以看到ConnectTimeoutReadTimeout默认是 1

@Bean
@ConditionalOnMissingBean
public IClientConfig ribbonClientConfig() {
  DefaultClientConfigImpl config = new DefaultClientConfigImpl();
  config.loadProperties(this.name);
  config.set(CommonClientConfigKey.ConnectTimeout, 1000);
  config.set(CommonClientConfigKey.ReadTimeout, 1000);
  config.set(CommonClientConfigKey.GZipPayload, true);
  return config;
}

在配置文件中,我们配置上ribbon的超时时间,接口就不会报错

ribbon:
  ConnectTimeout: 3000
  ReadTimeout: 5000

openfign 的超时时间是多少呢?默认的连接超时为 10 秒,读超时为 60

public Options() {
  this(10L, TimeUnit.SECONDS, 60L, TimeUnit.SECONDS, true);
}

如果 ribbon 为默认的超时时间,设置 openfeign 的连接超时时间为 3 秒,读超时时间为 5 秒

feign:
  client:
    config:
      default:
        connectTimeout: 3000
        readTimeout: 5000

可以发现接口也不会报错


如果设置 openfeign 的连接超时时间设置为 2 秒,读超时时间设置为 3 秒;ribbon 的连接超时时间设置为 5 秒,读超时时间设置为 6 秒。

feign:
  client:
    config:
      default:
        connectTimeout: 2000
        readTimeout: 3000
ribbon:
  ConnectTimeout: 5000
  ReadTimeout: 6000

并且 provider 接口修改为睡眠 5 秒,也就是超过了 openfeign 的超时时间,没有超过 ribbon 的超时时间

@GetMapping("/hello")
public String hello() {
  try {
      TimeUnit.SECONDS.sleep(5);
  } catch (InterruptedException e) {
      e.printStackTrace();
  }
  return "provider hello";
}

结果接口还是报错了!java.net.SocketTimeoutException: Read timed out


通过以上的校验,可以发现有三点:

  • openfignribbon 都不设置超时时间的情况下,以ribbon为准,默认的连接超时和读超时都为 1
  • openfign设置超时时间,ribbon不设置,则以 openfign 为准
  • openfignribbon 都设置了超时时间,则以 openfign 为准

欢迎小伙伴们积极指正和讨论,一起共同成长。

posted @ 2022-10-29 10:41  咖啡因的取悦  阅读(136)  评论(0)    收藏  举报