springcloud之Feign超时问题(Read timed out executing POST http://***)

问题背景

最近公司项目有个功能需进行三层Feign调用,且还要调外部接口,延迟挺大,造成Feign一直提示Read timed out executing POST

feign.RetryableException: Read timed out executing POST http://******
        at feign.FeignException.errorExecuting(FeignException.java:67)
        at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:104)
        at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
        at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
        at com.sun.proxy.$Proxy113.getBaseRow(Unknown Source)
Caused by: java.net.SocketTimeoutException: Read timed out
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
        at java.net.SocketInputStream.read(SocketInputStream.java:170)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
        at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
        at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:704)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:647)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1569)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
        at feign.Client$Default.convertResponse(Client.java:152)
        at feign.Client$Default.execute(Client.java:74)

解决方案

首先,我们看下Feign的简介

Feign 是一个声明式的web服务客户端,这便得编写web服务客户端更容易,使用Feign 创建一个接口并对它进行注解,它具有可插拔的注解支持包括Feign注解与JAX-RS注解,Feign还支持可插拔的编码器与解码器,Spring Cloud 增加了对 Spring MVC的注解,Spring Web 默认使用了HttpMessageConverters, Spring Cloud 集成 Ribbon 和 Eureka 提供的负载均衡的HTTP客户端 Feign.

这么说吧,Feign接口调用分两层,Ribbon的调用Hystrix调用,理论上设置Ribbon的时间即可,但是Ribbon的超时时间和Hystrix的超时时间需要结合起来,按照木桶原则最低的就是Feign的超时时间,建议最好配置超时时间一致。经过配置一下application设置后,完美解决了问题。因为第三方接口中需要3~20秒不等的时间,所以这个数值也是根据自己的业务系统情况设置的。

application.xml

#hystrix的超时时间
hystrix:
    command:
        default:
            execution:
              timeout:
                enabled: true
              isolation:
                    thread:
                        timeoutInMilliseconds: 30000
#ribbon的超时时间
ribbon:
  ReadTimeout: 30000
  ConnectTimeout: 30000
©️2020 CSDN 皮肤主题: 成长之路 设计师:Amelia_0503 返回首页