定时清理httpclient 闲置连接代码和http异常请求接口的开发

1、清理代码: 

// 定时清理http client 闲置连接
	private static class IdleConnectionEvictor implements Runnable {
		private final NHttpClientConnectionManager connMgr;

		public IdleConnectionEvictor(NHttpClientConnectionManager connMgr) {
			this.connMgr = connMgr;
		}

		@Override
		public void run() {
			try {
				long beginClosseTime = System.currentTimeMillis();
				// Close expired connections
				connMgr.closeExpiredConnections();
				// 关闭闲置 10 分钟的连接
				//connMgr.closeIdleConnections(600_000, TimeUnit.MILLISECONDS);
				connMgr.closeIdleConnections(600, TimeUnit.SECONDS);
				long took = System.currentTimeMillis() - beginClosseTime;
				if (took > 30) {
					logger.warn("IdleConnectionEvictor took too much time to close expire connections, took: {}(ms)",
							took);
				}
			} catch (Throwable ex) {
				logger.error("AbtestClient IdleConnectionEvictor got error", ex);
			}
		}
	}

2、调用代码

private void initHttpAsyncClient() {
		ConnectionKeepAliveStrategy keepAliveStrategy = (response, context) -> 600_000;

		ConnectingIOReactor ioReactor = null;
		try {
			IOReactorConfig config = IOReactorConfig.custom().setSelectInterval(httpAsyncClientSelectInterval)
					.setIoThreadCount(Runtime.getRuntime().availableProcessors()).build();
			ioReactor = new DefaultConnectingIOReactor(config);
		} catch (IOReactorException e) {
			logger.error("Abtestclent io reactor init failed,ex:{}", e.getMessage());
			throw new RuntimeException(e);
		}

		PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
		cm.setDefaultMaxPerRoute(3000);
		cm.setMaxTotal(6000);

		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectionRequestTimeout(httpAsyncClientConnectionRequestTimeout)
				.setConnectTimeout(httpAsyncClientConnectTimeout).setSocketTimeout(httpAsyncClientSocketTimeout)
				.build();

		httpAsyncClient = HttpAsyncClientBuilder.create().setConnectionManager(cm)
				.setKeepAliveStrategy(keepAliveStrategy).setDefaultRequestConfig(requestConfig)
				.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("AbtestClient").build()).build();
		httpAsyncClient.start();

		IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
		scheduler.scheduleAtFixedRate(connEvictor, 10, 10, TimeUnit.SECONDS);
	}

异步请求

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Apache HttpClient 发送 HTTPHTTPS 请求的示例代码: 1. 发送 HTTP 请求 ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://www.example.com"); HttpResponse httpResponse = httpClient.execute(httpGet); System.out.println(httpResponse.getStatusLine().getStatusCode()); // 打印响应状态码 } } ``` 2. 发送 HTTPS 请求 ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.impl.client.HttpClients; import javax.net.ssl.SSLContext; public class HttpClientExample { public static void main(String[] args) throws Exception { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificate, authType) -> true) .build(); HttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); HttpGet httpGet = new HttpGet("https://www.example.com"); HttpResponse httpResponse = httpClient.execute(httpGet); System.out.println(httpResponse.getStatusLine().getStatusCode()); // 打印响应状态码 } } ``` 注意事项: - HTTPS 请求需要设置 SSLContext 和 SSLHostnameVerifier; - SSLContext 的 TrustManager 应该接受所有证书,这不安全,建议修改为验证证书; - SSLHostnameVerifier 应该使用严格的 HostnameVerifier,这里为了简单只使用了 NoopHostnameVerifier。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值