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

}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

elasticsearch RestHighLevelClient Client 配置

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭