elasticsearch RestHighLevelClient Client 连接池配置

@Slf4j
@Configuration
@AutoConfigureAfter(ElasticSearchProperties.class)
public class ElasticSearchConfig extends AbstractFactoryBean {
 
 
    @Autowired
    private ElasticSearchProperties elasticSearchProperties;
    private RestHighLevelClient client;
    static final String COLON = ":";
    static final String COMMA = ",";
 
    @Override
    public void destroy() {
        try {
            log.info("Closing elasticSearch  client");
            if (client != null) {
                client.close();
            }
        } catch (final Exception e) {
            log.error("Error closing ElasticSearch client: ", e);
        }
    }
 
    @Override
    public Class<RestHighLevelClient> getObjectType() {
        return RestHighLevelClient.class;
    }
 
    @Override
    public boolean isSingleton() {
        return true;
    }
 
    @Override
    public RestHighLevelClient createInstance() throws IOReactorException {
        return buildClient();
    }
 
    private RestHighLevelClient buildClient() throws IOReactorException {
 
        Assert.hasText(elasticSearchProperties.getClusterNodes(), "[Assertion failed] clusterNodes settings missing.");
 
        String[] nodes = split(elasticSearchProperties.getClusterNodes(), COMMA);
        HttpHost[] hosts = new HttpHost[nodes.length];
        for (int i = 0, j = nodes.length; i < j; i++) {
            String hostName = substringBeforeLast(nodes[i], COLON);
            String port = substringAfterLast(nodes[i], COLON);
            Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
            Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
            log.info("adding transport node : " + nodes[i]);
            hosts[i] = new HttpHost(hostName, Integer.valueOf(port));
        }
 
        final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(elasticSearchProperties
                .getIoReactor()
                .getIoThreadCount()).setConnectTimeout(10).setRcvBufSize(5).setSoKeepAlive(true).build();
        final PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(new
                DefaultConnectingIOReactor(ioReactorConfig));
        connManager.setMaxTotal(100);
        connManager.setDefaultMaxPerRoute(100);
 
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(elasticSearchProperties.getBasic().getUsername(),
                        elasticSearchProperties.getBasic().getUserpass()));
        RestClientBuilder builder = RestClient.builder(hosts).setHttpClientConfigCallback(callback -> {
            callback.disableAuthCaching();
            return callback.setKeepAliveStrategy((response, context) -> {
                Args.notNull(response, "HTTP response");
                final HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    final HeaderElement he = it.nextElement();
                    final String param = he.getName();
                    final String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch (final NumberFormatException ignore) {
                        }
                    }
                }
                return 10 * 1000;
            }).setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(connManager);
        }).setRequestConfigCallback(requestConfigBuilder -> {
            return requestConfigBuilder.setConnectTimeout(elasticSearchProperties.getRequest().getConnectTimeout())
                    .setSocketTimeout(elasticSearchProperties.getRequest().getSocketTimeout())
                    .setConnectionRequestTimeout(elasticSearchProperties.getRequest().getConnectionRequestTimeout());
        }).setMaxRetryTimeoutMillis(elasticSearchProperties.getRequest().getMaxRetryTimeoutMillis());
        client = new RestHighLevelClient(builder);
        return client;
    }
 
}

IOReactorConfig.custom()

.setIoThreadCount(elasticSearchProperties.getIoReactor().getIoThreadCount())

.setConnectTimeout(10)

.setRcvBufSize(5)

.setSoKeepAlive(true)

 .build();

NIO中的配置,建议IoThreadCount设置为Runtime.getRuntime().availableProcessors()

SoKeepAlive设置为true.

猜你喜欢

转载自blog.csdn.net/qian_348840260/article/details/106948539
今日推荐