elasticsearch RestHighLevelClient Client 配置

/**
 * 描述:
 *
 * @author liweigao
 * @create 2018-05-15 上午9:30
 */
@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;
    }

}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值