定时清理httpclient 闲置连接代码

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);
	}

你可能感兴趣的:(前端,服务器,运维)