我们在Spring-Ws中使用Http Client 4.5.x,并通过webServiceTemplate.marshalSendAndReceive(requestObject)
方法发出请求。我们希望有一个可靠的连接超时值,但是目前遇到了here in section 8 (DNS round robin)中描述的问题,其中尝试了多个IP地址,因此超时是不可预测的。是否有一些简单的方法可以仅使用Spring-ws和Http Client库在特定时间后设置硬超时,还是需要某种自定义超时?
案例:连接超时设置为1秒(该方法的实际超时为4秒-是否可以使用Spring / Http客户端库将方法超时设置为1秒?)
应用程序日志(Http客户端日志设置为DEBUG
):
16:45:02 (org.apache.http.impl.execchain.MainClientExec) Opening connection {}->http://salesforce.com:448
16:45:02 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connecting to salesforce.com/96.43.149.26:448
16:45:03 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connect to salesforce.com/96.43.149.26:448 timed out. Connection will be retried using another IP address
16:45:03 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connecting to salesforce.com/96.43.145.26:448
16:45:04 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connect to salesforce.com/96.43.145.26:448 timed out. Connection will be retried using another IP address
16:45:04 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connecting to salesforce.com/96.43.144.26:448
16:45:05 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connect to salesforce.com/96.43.144.26:448 timed out. Connection will be retried using another IP address
16:45:05 (org.apache.http.impl.conn.DefaultHttpClientConnectionOperator) Connecting to salesforce.com/96.43.148.26:448
16:45:06 (org.apache.http.impl.conn.DefaultManagedHttpClientConnection) http-outgoing-0: Shutdown connection
Http客户bean:
<bean id="httpClientBean" class="org.apache.http.client.HttpClient" factory-bean="httpClientFactory" factory-method="getHttpClient" />
Http工厂代码(通过Spring依赖注入设置的连接超时值):
public class HttpFactory {
private int connectionTimeout;
public HttpFactory(int connectionTimeout, ...) {
this.connectionTimeout = connectionTimeout;
...
}
...
public HttpClient getHttpClient() {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
...
RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(this.connectionTimeout);
clientBuilder.setDefaultRequestConfig(configBuilder.build());
...
return clientBuilder.build();
}
}
Web服务模板bean:
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
...
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<constructor-arg index="0">
<ref bean="httpClientBean" />
</constructor-arg>
</bean>
</property>
</bean>
服务代码(我们希望此方法调用花费X秒,而不是2x或3x秒):
// we want this method call to take ~1 second, not ~4 seconds (i.e. similar to the connection timeout value, not a multiplier)
Object obj = webServiceTemplate.marshalSendAndReceive(requestDocument);
答案 0 :(得分:0)
有两个选择
构建自定义ClientConnectionOperator
构建自定义DnsResolver
。这个选项要简单得多。
CloseableHttpClient client = HttpClients.custom()
.setDnsResolver(host -> new InetAddress[] { InetAddress.getByName(host) })
.build();