首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Camel http组件不关闭连接- Close_Wait

Camel http组件不关闭连接- Close_Wait
EN

Stack Overflow用户
提问于 2014-09-25 18:35:28
回答 1查看 3.1K关注 0票数 7

Camel http组件不能正确关闭连接吗?

在下面的路由中,我观察到正在服务器上创建连接,但没有终止连接。过了一会儿,这引起了一个问题。

代码语言:javascript
运行
复制
java.io.IOException: Too many open files

路线:

代码语言:javascript
运行
复制
from("seda:testSeda?concurrentConsumers=20")
    .setHeader("Connection", constant("Close"))
    .to("http://testServer/testFile.xml?authMethod=Basic&throwExceptionOnFailure=false&authUsername=user&authPassword=password")
    .to("file://abc")
.end();

连接在Close_Wait状态下有什么想法吗?

我在使用版本2.14中的camel-http lib

EN

回答 1

Stack Overflow用户

发布于 2019-11-07 01:14:05

您可以覆盖Apache使用的默认HttpClient,并定义一个自定义的“保持活动策略”。

https://howtodoinjava.com/spring-boot2/resttemplate/resttemplate-httpclient-java-config/

下面的代码解决了我在生产中的问题:

@配置公共类AppConfiguration {

代码语言:javascript
运行
复制
@Autowired
private PoolingHttpClientConnectionManager poolingConnectionManager;
@Autowired
private ConnectionKeepAliveStrategy connectionKeepAliveStrategy;
@Autowired
private SSLConnectionSocketFactory sslContext;

@Bean
CamelContextConfiguration contextConfiguration() {
    return new CamelContextConfiguration() {
        @Override
        public void beforeApplicationStart(CamelContext context) {
            HttpComponent httpComponent = context.getComponent("https4", HttpComponent.class);

            httpComponent.setHttpClientConfigurer(new HttpClientConfigurer() {
                @Override
                public void configureHttpClient(HttpClientBuilder builder) {

                    builder.setSSLSocketFactory(sslContext);

                    RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslContext).build();

                    builder.setConnectionManager(poolingConnectionManager);
                    builder.setKeepAliveStrategy(connectionKeepAliveStrategy);
                }
            });
        }

        @Override
        public void afterApplicationStart(CamelContext arg0) {

        }

    };
}

}

@配置公共类HttpClientConfig {

代码语言:javascript
运行
复制
private static final int DEFAULT_KEEP_ALIVE_TIME_MILLIS = 20 * 1000;
private static final int CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS = 30;

@Value("${pathCertificado}")
private String pathCertificado;

private Logger logger = LoggerFactory.getLogger(HttpClientConfig.class);

@Bean
public PoolingHttpClientConnectionManager poolingConnectionManager() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(200);
    connectionManager.setDefaultMaxPerRoute(20);

    return connectionManager;
}

@Bean
public CloseableHttpClient httpClient() {
    RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(15000).build();

    return HttpClientBuilder.create().setSSLSocketFactory(this.getSSLContext())
            .setConnectionManager(this.poolingConnectionManager()).setDefaultRequestConfig(config)
            .setKeepAliveStrategy(this.connectionKeepAliveStrategy()).build();

}

@Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
    return new ConnectionKeepAliveStrategy() {
        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();

                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return DEFAULT_KEEP_ALIVE_TIME_MILLIS;
        }
    };
}

@Bean
public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
    return new Runnable() {
        @Override
        @Scheduled(fixedDelay = 10000)
        public void run() {
            if (connectionManager != null) {
                connectionManager.closeExpiredConnections();
                connectionManager.closeIdleConnections(CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS, TimeUnit.SECONDS);
            }
        }
    };
}

@Bean
public SSLConnectionSocketFactory getSSLContext() {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        try (FileInputStream jksFile = new FileInputStream(this.pathCertificado)) {
            keyStore.load(jksFile, "xxxxxx".toCharArray());
        }

        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(keyStore, acceptingTrustStrategy).build();

        return new SSLConnectionSocketFactory(sslContext);
    } catch (Exception e) {
        logger.error("Keystore load failed: " + this.pathCertificado, e);

        return null;
    }
}

}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26045702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档