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);}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/235479.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

pyCharm 创建一个FastApi web项目,实现接口调用

FastApi和Django区别 我这边演示项目使用的fastApi作为web框架&#xff0c;当然主流一般都是使用Django做web框架&#xff0c;但是Django是一个重量级web框架他有很多组件&#xff0c;如授权&#xff0c;分流等全套web功能。我这边呢只需要有个接口可以被别人调用&#xff0c;…

【超详细前后端项目搭建】前端vue3+ts项目(引入ElementPlus、Axios)、后端springboot搭建(创建接口操作mysql数据库)实现前后端联调

目录 前言一、前端项目1、使用vue脚手架创建项目1.1检查vue版本1.2 使用vue脚手架创建项目 2、删除项目多余文件&#xff0c;修改配置项目2.1、删除以下文件2.1、在views下创建index文件2.2、修改router/index.ts路由文件&#xff1a;2.3、修改App.vue文件&#xff1a;2.4、初始…

气候变化与环境保护:全球研究与未来趋势

导言 气候变化和环境保护是当今社会亟待解决的全球性难题。本文将深入探讨这一主要流行研究方向的发展历程、遇到的问题、解决过程&#xff0c;以及未来的可用范围&#xff0c;着重分析在各国的应用和未来的研究趋势&#xff0c;以探讨在哪些方面能够取得胜利&#xff0c;以及在…

大数据学习(29)-spark on yarn底层原理

&&大数据学习&& &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 承认自己的无知&#xff0c;乃是开启智慧的大门 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4dd;支持一下博主哦&#x1f91…

PySpark中DataFrame的join操作

内容导航 类别内容导航机器学习机器学习算法应用场景与评价指标机器学习算法—分类机器学习算法—回归机器学习算法—聚类机器学习算法—异常检测机器学习算法—时间序列数据可视化数据可视化—折线图数据可视化—箱线图数据可视化—柱状图数据可视化—饼图、环形图、雷达图统…

期货开平规则(期货交易开平规则解析)

什么是期货开平规则 期货开平规则&#xff0c;简单来说是指期货交易中的开仓和平仓所遵循的一系列规定。具体而言&#xff0c;开仓是指买入或卖出期货合约&#xff0c;建立一个新的持仓&#xff1b;平仓则是指买入或卖出相应数量的期货合约&#xff0c;用以解除原有持仓。开平…

什么是数据仪表板?数据可视化仪表盘怎么制作?

在数据经济时代&#xff0c;分析数据是每个企业做出最佳决策的关键。但是&#xff0c;手动分析和解释大量数据是不可行的。数据可视化对于分析数据中存在的各种有价值信息至关重要&#xff0c;包括可见趋势和隐藏趋势等。仪表盘显示可视化趋势和信息&#xff0c;例如 KPI、趋势…

xlsx-style使用中常见问题及解决办法

问题1. Can‘t resolve ‘./cptable‘ in ‘xxx\node_modules_xlsx 在vue.config.js中引入以下代码 configureWebpack: {externals: {./cptable: var cptable},}, 问题2. Can’t resolve ‘fs’ 在vue.config.js中引入以下代码 module.exports defineConfig({transpileDepe…

简易实现 STL--list

实现 list 的主要思想及过程 首先&#xff0c;实现过程中的所有代码必须放在自己定义的命名空间中。 定义一个结点的结构体类模板&#xff0c;结点的数据类型就应该是模板类型 T&#xff0c;定义的 next指针和 prev指针都应该是模板指针类型&#xff0c;并且结构体类中药有构…

微信小程序中wx:if 和 hidden的区别

wx:if 和 hidden的相同点 wx:if 与 hidden 都用来控制小程序元素的显示的 不同点 wx:if 1. 条件为 true 时显示 2. 当元素显示时渲染 3. 元素变为不显示时销毁元素 hidden&#xff1a; 1. 条件为 false 时显示 2. 当元素显示时渲染 3. 元素变为不显示时保留元素 4. 相…

2017年第六届数学建模国际赛小美赛A题飓风与全球变暖解题全过程文档及程序

2017年第六届数学建模国际赛小美赛 A题 飓风与全球变暖 原题再现&#xff1a; 飓风&#xff08;也包括在西北太平洋被称为“台风”的风暴以及在印度洋和西南太平洋被称为“严重热带气旋”&#xff09;具有极大的破坏性&#xff0c;往往造成数百人甚至数千人死亡。   许多气…

UE4移动端最小包优化实践

移动端对于包大小有着严苛的要求,然而UE哪怕是一个空工程打出来也有90+M,本文以一个复杂的工程为例,探索怎么把包大小降低到最小。 一、工程简介 工程包含代码、插件、资源、iOS原生库工程。 二、按官方文档进行基础优化 官方文档 1、勾选Use Pak File和Create comp…

YOLOv5性能评估指标->mAP、Precision、Recall、FPS、Confienc (讲解论文关注的主要指标)

简介 这篇博客&#xff0c;主要给大家讲解我们在训练yolov5时生成的结果文件中各个图片及其中指标的含义&#xff0c;帮助大家更深入的理解&#xff0c;以及我们在评估模型时和发表论文时主要关注的参数有那些。本文通过举例训练过程中的某一时间的结果来帮助大家理解&#xf…

npm安装依赖报错ERESOLVE unable to resolve dependency tree(我是在taro项目中)(node、npm 版本问题)

换了电脑之后新电脑安装包出错 &#x1f447;&#x1f447;&#x1f447; npm install 安装包报错 ERESOLVE unable to resolve dependency tree 百度后尝试使用 npm install --force 还是报错 参考 有人说是 node 版本和 npm 版本的问题 参考 新电脑 node版本&#xff1a;16.1…

kotlin第三方库记录

一、测试 除了JUnit与TestNG&#xff0c;下面两个框架提供了用kotlin编写测试的更有表现力的DSL 1.KotlinTest&#xff08;https://github.com/kotlintest/kotlintest&#xff09;——灵活的测试框架&#xff0c;它的灵感来自于ScalaTest&#xff0c;支持多种不同的编写测试的…

深度学习中聚类的“类”指的是什么

在深度学习中的聚类中&#xff0c;“类”指的是数据点的一个集合&#xff0c;这些数据点根据某种相似性标准被归为同一组。在聚类的上下文中&#xff0c;这些类通常被称为“簇”&#xff08;clusters&#xff09;。每个簇是数据集中的一个子集&#xff0c;簇内的元素相互之间比…

Unity闪屏Logo去除

1.新建一个C#脚本&#xff0c;命名为 “SkipSplashScreen” &#xff08;代码如下&#xff09;。 using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI;#if !UNITY_EDITOR using UnityEngine; using UnityEn…

ros2机器人常规控制流程

The joint_state_publisher reads the robot_description parameter from the parameter server, finds all of the non-fixed joints and publishes a JointState message with all those joints defined.也就是说如果我们不需要控制机器人运动&#xff0c;只需要一个节点就可…

自学精灵--专业的编程学习网站

这是我看过的最靠谱的编程学习网站&#xff0c;名字是&#xff1a;自学精灵&#xff0c;网站是&#xff1a;learn.skyofit.com。&#xff08;某度搜"自学精灵"也可找到此站&#xff0c;搜不到可以用必应搜&#xff09;。 自学精灵是全网最强的学习平台&#xff0c;我…

Oracle sql 把hjmc等于实施方案的,排序在第一,并且把sxh等于-1的排在最后

要将hjmc等于"实施方案"的行排序在第一&#xff0c;并将sxh等于-1的行排在最后&#xff0c;你可以使用ORDER BY子句来实现。假设你的数据表名为your_table_name&#xff0c;你可以使用以下SQL查询&#xff1a; SELECT * FROM your_table_name ORDER BY CASE WHEN hj…