xkcoding / spring-boot-demo

🚀一个用来深入学习并实战 Spring Boot 的项目。
https://parg.co/UZM
MIT License
33.18k stars 10.9k forks source link

elasticsearch-rest-high-level-client身份认证配置问题 #140

Open wulongchaii opened 4 years ago

wulongchaii commented 4 years ago

spring-boot-demo-elasticsearch-rest-high-level-client模块,ElasticsearchAutoConfiguration中对es身份认证的配置应该需要加到builder.setHttpClientConfigCallback里吧,按照现在的配置当我开启es的x-pack身份认证后还是会报权限错误。以下是我修改后的配置:

private static RestHighLevelClient getRestHighLevelClient(RestClientBuilder builder, ElasticsearchProperties elasticsearchProperties) {

        // Callback used the default {@link RequestConfig} being set to the {@link CloseableHttpClient}
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeout());
            requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeout());
            return requestConfigBuilder;
        });

        // Callback used to customize the {@link CloseableHttpClient} instance used by a {@link RestClient} instance.
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectTotal());
            httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectPerRoute());
            // Callback used the basic credential auth
            ElasticsearchProperties.Account account = elasticsearchProperties.getAccount();
            if (!StringUtils.isEmpty(account.getUsername()) && !StringUtils.isEmpty(account.getUsername())) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(account.getUsername(), account.getPassword()));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            return httpClientBuilder;
        });
        return new RestHighLevelClient(builder);
    }