OpenFeign在调用服务时默认等待1秒钟

1.演示OpenFeign调用服务超时示例


修改cloud-provider-payment8001项目中的PaymentController添加如下内容
调用这个接口会休眠3秒钟

  1. @GetMapping(value = "/payment/feign/timeout")
  2. public String paymentFeignTimeout() {
  3. try {
  4. TimeUnit.SECONDS.sleep(3);
  5. } catch (Exception e) {
  6. e.printStackTrace();
  7. }
  8. return serverPort;
  9. }

修改cloud-consumer-feign-order80项目中的PaymentFeignService添加如下内容

@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeout();

修改cloud-consumer-feign-order80项目中的OrderFeignController添加如下内容

@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout(){
    return paymentFeignService.paymentFeignTimeout();
}

启动Eureka注册中心:cloud-eureka-server7001,cloud-eureka-server7002
启动服务提供者:cloud-provider-payment8001
启动服务消费者:cloud-consumer-feign-order80
浏览器输入:http://localhost/consumer/payment/feign/timeout
image-20200319204022761.png

默认Feign客户端只等待一秒钟,但是服务端处理需要超过1秒钟,导致Feign客户端不想等待了,直接返回报错。为了避免这样的情况,有时候我们需要设置Feign客户端的超时控制。

2.在application.yml文件中开启超时配置


修改cloud-consumer-feign-order80项目中的application.yml配置文件增加如下内容

ribbon:
  #指的是建立连接后从服务器读取到可用资源所用的时间
  ReadTimeout:  5000
  #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
  ConnectTimeout: 5000

重启cloud-consumer-feign-order80项目
浏览器输入:http://localhost/consumer/payment/feign/timeout
此时就会成功返回结果