spring boot3.2 集成 es 8.x 版本工具类 支持认证与非认证的方式( jdk21)

主要maven 依赖 

     <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.11.2</version>
        </dependency>

工具类如下

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.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @author gaodd
 * @version 1.0
 * @description esClient 工具类
 * @date 2023/12/11 13:29
 **/
@Slf4j
public class EsRestClientUtil implements AutoCloseable {

    @Getter
    private static final EsRestClientUtil instance = new EsRestClientUtil();
    private EsRestClientUtil() {
        // 私有化构造方法,防止外部实例化对象
    }

    private final  ThreadLocal<RestClient> restClientTl = new ThreadLocal<>();

    private final  ThreadLocal<ElasticsearchTransport> elasticsearchTransportTl = new ThreadLocal<>();

    /**
     * 获取es Http类型的客户端
     *
     * @param host
     * @param port
     * @param login
     * @param password
     * @return
     */
    public  ElasticsearchClient getElasticsearchHttpClient(String host, int port, String login, String password) throws SSLException, NoSuchAlgorithmException, KeyManagementException {
        return getElasticsearchClient(null, host, port, login, password, null);
    }
    public  ElasticsearchClient getElasticsearchHttpsClient(String host, int port, String login, String password) throws SSLException, NoSuchAlgorithmException, KeyManagementException {
        return getElasticsearchClient("https", host, port, login, password, null);
    }
    /**
     * 关闭客户端
     */
    @Override
    public void close() {
        if (elasticsearchTransportTl.get() != null) {
            try {
                elasticsearchTransportTl.get().close();
                elasticsearchTransportTl.remove();
            } catch (IOException e) {
                log.error("关闭elasticsearchTransport异常", e);
            }
        }
        if (restClientTl.get() != null) {
            try {
                restClientTl.get().close();
                restClientTl.remove();
            } catch (IOException e) {
                log.error("关闭restClient异常", e);
            }
        }
    }

    /***
     *
     * @param schema  https 或 http
     * @param host   主机ip
     * @param port   端口
     * @param login  用户名
     * @param password 密码
     * @param fingerprint  证书指纹
     * @return ElasticsearchClient
     */
    public synchronized  ElasticsearchClient getElasticsearchClient(String schema, String host, int port, String login, String password, String fingerprint) throws SSLException, NoSuchAlgorithmException, KeyManagementException {

        RestClient restClient = getRestClient(schema, host, port, login, password, fingerprint);
        var elasticsearchTransport = new RestClientTransport(
                restClient,
                new JacksonJsonpMapper()
        );
        restClientTl.set(restClient);
        elasticsearchTransportTl.set(elasticsearchTransport);
        return new ElasticsearchClient(elasticsearchTransport);

    }

    private  RestClient getRestClient(String schema, String host, int port, String login, String password, String fingerprint) throws NoSuchAlgorithmException, KeyManagementException {
       final var credsProv = new BasicCredentialsProvider();
        credsProv.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(login, password)
        );
        if ("https".equals(schema)) {
            final var sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, TRUST_ALL_CERTS, new SecureRandom());
//            SSLContext sslContext = TransportUtils
//                    .sslContextFromCaFingerprint(fingerprint);
            return RestClient
                    .builder(new HttpHost(host, port, schema))
                    .setHttpClientConfigCallback(hc -> hc
                            .setSSLContext(sc)
                            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                            .setDefaultCredentialsProvider(credsProv)).build();
        }
        return RestClient
                .builder(new HttpHost(host, port, schema))
                .setHttpClientConfigCallback(hc -> hc
                        .setDefaultCredentialsProvider(credsProv)
                )
                .build();
    }

    private  final TrustManager[] TRUST_ALL_CERTS = new TrustManager[]{new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
            log.info("all trusted");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
            log.info("no need to Trusted");
        }
    }};

}

使用方式如下 使用 try with resource 的方式实现自动关闭流

import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
import co.elastic.clients.elasticsearch.core.GetResponse;;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.io.IOException;
import java.io.Serializable;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * @author gaodd
 * @description EsRestClientUtil     工具类使用示例
 * @date 2023/12/8 10:44
 **/

public class EsClientDemoTest {

           @Test
           public void  testhttp(){

               String host = "172.xx.xx.xx";

               int port = 9200;

               String login = "elastic";

               String password = "pswd";

                // Create the transport and the API client
               try(EsRestClientUtil esRestClientUtil = EsRestClientUtil.getInstance()) {
                var esClient =   esRestClientUtil.getElasticsearchHttpClient( host, port, login, password);
 ElasticsearchClusterClient cluster = esClient.cluster();
                   log.info("Indexed with version " + cluster.health());
               } catch (IOException e) {
                   throw new RuntimeException(e);
               } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
               } catch (KeyManagementException e) {
                   throw new RuntimeException(e);
               }
           }
           @Test
           public void  testhttps(){

               String host = "172.xx.xx.xxx";

               int port = 9200;

               String login = "elastic";

               String password = "pswd";

                // Create the transport and the API client
               try(EsRestClientUtil esRestClientUtil = EsRestClientUtil.getInstance()) {
                var esClient =   esRestClientUtil.getElasticsearchHttpsClient( host, port, login, password);
                   ElasticsearchClusterClient cluster = esClient.cluster();
                   log.info("Indexed with version " + cluster.health());

               } catch (IOException e) {
                   throw new RuntimeException(e);
               } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
               } catch (KeyManagementException e) {
                   throw new RuntimeException(e);
               }
           }

         
}

相关推荐

  1. jdk8jdk17区别。springboot2.xspringboot3.x区别

    2023-12-21 12:58:04       22 阅读
  2. Springboot集成token认证

    2023-12-21 12:58:04       11 阅读
  3. 【DevOps工具篇】Keycloak中设置OpenLDAP认证集成

    2023-12-21 12:58:04       15 阅读
  4. SpringBoot集成ClickHouse,含集成kerberos认证

    2023-12-21 12:58:04       10 阅读
  5. springboot jdk版本找不到8怎么办?

    2023-12-21 12:58:04       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-21 12:58:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-21 12:58:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-21 12:58:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-21 12:58:04       20 阅读

热门阅读

  1. Vue的网络请求、插槽、Vuex

    2023-12-21 12:58:04       44 阅读
  2. git或svn提交消息时,fix、feat等命令的含义

    2023-12-21 12:58:04       43 阅读
  3. 爬虫scrapy管道的使用

    2023-12-21 12:58:04       36 阅读
  4. 面试经典150题(38-41)

    2023-12-21 12:58:04       33 阅读
  5. golang开发--beego入门

    2023-12-21 12:58:04       30 阅读
  6. SpringBoot集成Drools

    2023-12-21 12:58:04       36 阅读
  7. 【单元测试】测还是不测,这是一个问题

    2023-12-21 12:58:04       35 阅读
  8. 【数据库模拟题目集】判断题

    2023-12-21 12:58:04       41 阅读