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

相关文章

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

SpringBoot整合OpenFeign的完整指南

《SpringBoot整合OpenFeign的完整指南》OpenFeign是由Netflix开发的一个声明式Web服务客户端,它使得编写HTTP客户端变得更加简单,本文为大家介绍了SpringBoot... 目录什么是OpenFeign环境准备创建 Spring Boot 项目添加依赖启用 OpenFeig

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

SpringBoot中配置文件的加载顺序解读

《SpringBoot中配置文件的加载顺序解读》:本文主要介绍SpringBoot中配置文件的加载顺序,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录SpringBoot配置文件的加载顺序1、命令⾏参数2、Java系统属性3、操作系统环境变量5、项目【外部】的ap

SpringBoot UserAgentUtils获取用户浏览器的用法

《SpringBootUserAgentUtils获取用户浏览器的用法》UserAgentUtils是于处理用户代理(User-Agent)字符串的工具类,一般用于解析和处理浏览器、操作系统以及设备... 目录介绍效果图依赖封装客户端工具封装IP工具实体类获取设备信息入库介绍UserAgentUtils

Spring 中的循环引用问题解决方法

《Spring中的循环引用问题解决方法》:本文主要介绍Spring中的循环引用问题解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录什么是循环引用?循环依赖三级缓存解决循环依赖二级缓存三级缓存本章来聊聊Spring 中的循环引用问题该如何解决。这里聊