Customize HTTPClient for Spring Cloud Open Feign



我想使用Spring Cloud Open Feign做一些像下面这样的事情

  • 创建池HTTP客户端连接管理器
  • 让一个空闲的连接管理器监视线程进行内务管理
  • 避免CLOSE_WAIT,总是在消耗body后关闭响应

HTTP客户端代码看起来像


static class IdleConnectionMonitorThread extends Thread {

private volatile boolean shutdown;
private PoolingHttpClientConnectionManager connMgr;

public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
super();
this.setName("TCP-Ideal-Monitroing-Thread");
this.connMgr = connMgr;
}

@Override
public void run() {
try {
while (!shutdown) {
sleep(TimeUnit.MINUTES.toMillis(1));
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 60 sec
connMgr.closeIdleConnections(10, TimeUnit.MINUTES);
}
} catch (InterruptedException ex) {
// terminate
}
}

public void shutdown() {
shutdown = true;
}

}

public void createClient() throws Exception {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(10, TimeUnit.MINUTES);
connectionManager.setMaxTotal(1000);
connectionManager.setDefaultMaxPerRoute(20);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build()) 

Thread th = new IdleConnectionMonitorThread(connectionManager);

th.start();

}

我想这样做的原因是因为我可以看到很多HTTP连接是打开的,而不是正确关闭,由于我得到一些间歇性的错误。

是否有一种方法来定制Spring Cloud Open Feign的HTTP客户端基于上面提到的?

如何自定义,请参考以下链接。https://codingnconcepts.com/spring-boot/change-default-feign-client-implementation/

<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
IN application.properties or yaml file 
feign.httpclient.enabled: true

@Configuration
public class FeignClientConfig {
@Bean
public CloseableHttpClient feignClient() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(10, TimeUnit.MINUTES);
connectionManager.setMaxTotal(1000);
connectionManager.setDefaultMaxPerRoute(20);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build()) 

Thread th = new IdleConnectionMonitorThread(connectionManager);

th.start();
return httpClient;
}
}
static class IdleConnectionMonitorThread extends Thread {

private volatile boolean shutdown;
private PoolingHttpClientConnectionManager connMgr;

public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
super();
this.setName("TCP-Ideal-Monitroing-Thread");
this.connMgr = connMgr;
}

@Override
public void run() {
try {
while (!shutdown) {
sleep(TimeUnit.MINUTES.toMillis(1));
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 60 sec
connMgr.closeIdleConnections(10, TimeUnit.MINUTES);
}
} catch (InterruptedException ex) {
// terminate
}
}

public void shutdown() {
shutdown = true;
}

}

相关内容

  • 没有找到相关文章

最新更新