Spring 外部客户端超时

Spring external client timeout

在我们的 Spring 应用程序中,我们依赖于外部系统。 我们想为对该系统的请求设置超时,但不知道如何配置它。

我们使用这个:

   return clientBuilder.build()
            .target(baseUrl)
            .register(jsonProvider)
            .register(jsonAcceptHeaderClientRequestFilter)
            .register(new LoggingFilter());

我试过这个: How to set the connection and read timeout with Jersey 2.x? 和许多其他建议,但无法实现。如有任何建议,我们将不胜感激。

更新不起作用的东西:

.property("http.connection.timeout", 1)
.property("http.receive.timeout", 1)

以及

.property(ClientProperties.CONNECT_TIMEOUT,1)
.property(ClientProperties.READ_TIMEOUT,1)

您可以使用 server.connection-timeout,但这会为所有请求设置超时,而不仅仅是向 外部系统 发出的请求。

server.connection-timeout= # Time that connectors wait for another HTTP request before closing the connection. When not set, the connector's container-specific default is used. Use a value of -1 to indicate no (that is, an infinite) timeout.

Reference

正如您问题中链接的答案所确认的那样,@df778899 的评论之一以及根据我的测试,以下用法适用于 jersey 客户端

target(baseUrl)
.property(ClientProperties.CONNECT_TIMEOUT, 1000)
.property(ClientProperties.READ_TIMEOUT, 1000)

如果外部服务器未能在设定时间内响应,则产生java.net.SocketTimeoutException

对于,Apache CXF client, I have tested below snippet and it works for read timeouts. And, this is the official reference。在该页面中搜索以下代码段中使用的参数。

注意:对于支持此功能时的版本,请检查此 JIRA

target(baseUrl)
.property("http.connection.timeout", 5000)
.property("http.receive.timeout", 5000)

更新 : 以下内容可能不是OP所要求的,但出于学术考虑保留

我的直觉是,您追求的是不同的目标。在我看来,您的外部系统实际上正在响应,但可能比您期望的速度慢,或者响应本身更大,这反过来需要比您期望的更长的时间来消耗?

在这种情况下,您可以调整超时参数。但是,它们在循环套接字读取的基础上工作。因此,假设您将超时设置为 X 并且您的响应数据为 Y 字节。读取速度慢可能意味着 socket.read() 调用输出数据,但内容为 1/2 字节。 X 适用于每次阅读。因此,理论上完整读取可能需要 X*Y 毫秒。

如果以上确实是您的问题,那么您可能需要使用外部计时器来解决此问题。例如,您可以:

  1. 通过ExecutorService.submit(Callable< T> task)
  2. 进行外部服务调用
  3. 然后,调用结果 Future.get(long timeout, TimeUnit unit)