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.

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
对于在Spring Boot中使用Elasticsearch连接池,你可以使用Spring Data Elasticsearch提供的自动配置功能来实现。 首先,确保在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 接下来,在`application.properties`或`application.yml`文件中配置Elasticsearch连接信息,例如: ```properties spring.data.elasticsearch.cluster-nodes=localhost:9200 spring.data.elasticsearch.cluster-name=my-cluster ``` 然后,创建一个Elasticsearch配置类,例如`ElasticsearchConfig.java`: ```java import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.client.ClientConfiguration; import org.springframework.data.elasticsearch.client.RestClients; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; @Configuration public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { @Value("${spring.data.elasticsearch.cluster-nodes}") private String clusterNodes; @Override @Bean public RestHighLevelClient elasticsearchClient() { final ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo(clusterNodes) .build(); return RestClients.create(clientConfiguration).rest(); } } ``` 最后,你可以在你的服务类或控制器中注入`RestHighLevelClient`来使用Elasticsearch连接池,例如: ```java import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MyService { private final RestHighLevelClient elasticsearchClient; @Autowired public MyService(RestHighLevelClient elasticsearchClient) { this.elasticsearchClient = elasticsearchClient; } // 使用elasticsearchClient进行Elasticsearch操作 } ``` 这样就完成了Spring Boot与Elasticsearch连接池配置和使用。你可以根据自己的需求进行进一步的配置和操作。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值