欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

springboot2.7 整合 es8 https 绕过证书访问集群配置类的方法

最编程 2024-03-23 21:59:03
...
import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Configuration
@Slf4j
@RequiredArgsConstructor
public class ElasticSearchConfig {

    private final ElasticsearchProperties elasticsearchProperties;

    @Bean
    public RestClient restClient() throws Exception {
        List<String> urlList = elasticsearchProperties.getUris();
        HttpHost[] httpHosts = new HttpHost[urlList.size()];
        for (int i = 0; i < urlList.size(); i++) {
            String item = urlList.get(i);
            URI uri = URI.create(item);
            httpHosts[i] = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword()));

        SSLContext sslContext = SSLContextBuilder.create()
            .loadTrustMaterial((chain, authType) -> true)
            .build();

        return RestClient.builder(httpHosts)
            .setHttpClientConfigCallback(httpClientBuilder -> {
                // 添加拦截器来打印请求
                httpClientBuilder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> {
                    RequestLine requestLine = request.getRequestLine();
                    String uri = requestLine.getUri();
                    String method = requestLine.getMethod();
                    String body = null;
                    if (request instanceof HttpRequestWrapper) {
                        HttpRequest originalRequest = ((HttpRequestWrapper) request).getOriginal();
                        if (originalRequest instanceof HttpEntityEnclosingRequest) {
                            HttpEntity entity = ((HttpEntityEnclosingRequest) originalRequest).getEntity();
                            if (entity != null) {
                                ContentType contentType = ContentType.get(entity);
                                if (contentType != null && StrUtil.contains(contentType.getMimeType(), "json")) {
                                    body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                                }
                            }
                        }
                    }
                    log.info("发送es请求,Method:{},uri:{},请求体:{}", method, uri, body);
                });
                httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .setSSLContext(sslContext)
                    .setDefaultCredentialsProvider(credentialsProvider);
                return httpClientBuilder;
            })
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                .setConnectTimeout(5000)
                .setSocketTimeout(60000)).build();
    }


    @Bean
    public ElasticsearchClient elasticsearchClient() throws Exception {
        RestClient restClient = restClient();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }


}