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 Spring 中的监听器Listener详解与实战教程

《JavaSpring中的监听器Listener详解与实战教程》Spring提供了多种监听器机制,可以用于监听应用生命周期、会话生命周期和请求处理过程中的事件,:本文主要介绍JavaSprin... 目录一、监听器的作用1.1 应用生命周期管理1.2 会话管理1.3 请求处理监控二、创建监听器2.1 Ser

windows系统上如何进行maven安装和配置方式

《windows系统上如何进行maven安装和配置方式》:本文主要介绍windows系统上如何进行maven安装和配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. Maven 简介2. maven的下载与安装2.1 下载 Maven2.2 Maven安装2.

Redis指南及6.2.x版本安装过程

《Redis指南及6.2.x版本安装过程》Redis是完全开源免费的,遵守BSD协议,是一个高性能(NOSQL)的key-value数据库,Redis是一个开源的使用ANSIC语言编写、支持网络、... 目录概述Redis特点Redis应用场景缓存缓存分布式会话分布式锁社交网络最新列表Redis各版本介绍旧

IIS 7.0 及更高版本中的 FTP 状态代码

《IIS7.0及更高版本中的FTP状态代码》本文介绍IIS7.0中的FTP状态代码,方便大家在使用iis中发现ftp的问题... 简介尝试使用 FTP 访问运行 Internet Information Services (IIS) 7.0 或更高版本的服务器上的内容时,IIS 将返回指示响应状态的数字代

JVisualVM之Java性能监控与调优利器详解

《JVisualVM之Java性能监控与调优利器详解》本文将详细介绍JVisualVM的使用方法,并结合实际案例展示如何利用它进行性能调优,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录1. JVisualVM简介2. JVisualVM的安装与启动2.1 启动JVisualVM2

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Python使用FFmpeg实现高效音频格式转换工具

《Python使用FFmpeg实现高效音频格式转换工具》在数字音频处理领域,音频格式转换是一项基础但至关重要的功能,本文主要为大家介绍了Python如何使用FFmpeg实现强大功能的图形化音频转换工具... 目录概述功能详解软件效果展示主界面布局转换过程截图完成提示开发步骤详解1. 环境准备2. 项目功能结

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

MySQL 添加索引5种方式示例详解(实用sql代码)

《MySQL添加索引5种方式示例详解(实用sql代码)》在MySQL数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中,下面给大家分享MySQL添加索引5种方式示例详解(实用sql代码),... 在mysql数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中。索引可以在创建表时定义,也可