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

本文主要是介绍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 {@Getterprivate 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);}/*** 关闭客户端*/@Overridepublic 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() {@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[]{};}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) {log.info("all trusted");}@Overridepublic 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 {@Testpublic void  testhttp(){String host = "172.xx.xx.xx";int port = 9200;String login = "elastic";String password = "pswd";// Create the transport and the API clienttry(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);}}@Testpublic void  testhttps(){String host = "172.xx.xx.xxx";int port = 9200;String login = "elastic";String password = "pswd";// Create the transport and the API clienttry(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);}}}

这篇关于spring boot3.2 集成 es 8.x 版本工具类 支持认证与非认证的方式( jdk21)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/531373

相关文章

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法

Java中List的contains()方法的使用小结

《Java中List的contains()方法的使用小结》List的contains()方法用于检查列表中是否包含指定的元素,借助equals()方法进行判断,下面就来介绍Java中List的c... 目录详细展开1. 方法签名2. 工作原理3. 使用示例4. 注意事项总结结论:List 的 contain

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis