定时清理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);
	}

异步请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值