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

相关文章

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

Spring Cloud Hystrix原理与注意事项小结

《SpringCloudHystrix原理与注意事项小结》本文介绍了Hystrix的基本概念、工作原理以及其在实际开发中的应用方式,通过对Hystrix的深入学习,开发者可以在分布式系统中实现精细... 目录一、Spring Cloud Hystrix概述和设计目标(一)Spring Cloud Hystr

springboot3.4和mybatis plus的版本问题的解决

《springboot3.4和mybatisplus的版本问题的解决》本文主要介绍了springboot3.4和mybatisplus的版本问题的解决,主要由于SpringBoot3.4与MyBat... 报错1:spring-boot-starter/3.4.0/spring-boot-starter-

Spring Boot整合消息队列RabbitMQ的实现示例

《SpringBoot整合消息队列RabbitMQ的实现示例》本文主要介绍了SpringBoot整合消息队列RabbitMQ的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录RabbitMQ 简介与安装1. RabbitMQ 简介2. RabbitMQ 安装Spring

nginx upstream六种方式分配小结

《nginxupstream六种方式分配小结》本文主要介绍了nginxupstream六种方式分配小结,包括轮询、加权轮询、IP哈希、公平轮询、URL哈希和备份服务器,具有一定的参考价格,感兴趣的可... 目录1 轮询(默认)2 weight3 ip_hash4 fair(第三方)5 url_hash(第三

springMVC返回Http响应的实现

《springMVC返回Http响应的实现》本文主要介绍了在SpringBoot中使用@Controller、@ResponseBody和@RestController注解进行HTTP响应返回的方法,... 目录一、返回页面二、@Controller和@ResponseBody与RestController

JAVA集成本地部署的DeepSeek的图文教程

《JAVA集成本地部署的DeepSeek的图文教程》本文主要介绍了JAVA集成本地部署的DeepSeek的图文教程,包含配置环境变量及下载DeepSeek-R1模型并启动,具有一定的参考价值,感兴趣的... 目录一、下载部署DeepSeek1.下载ollama2.下载DeepSeek-R1模型并启动 二、J

springboot rocketmq配置生产者和消息者的步骤

《springbootrocketmq配置生产者和消息者的步骤》本文介绍了如何在SpringBoot中集成RocketMQ,包括添加依赖、配置application.yml、创建生产者和消费者,并展... 目录1. 添加依赖2. 配置application.yml3. 创建生产者4. 创建消费者5. 使用在

Spring Retry 实现乐观锁重试实践记录

《SpringRetry实现乐观锁重试实践记录》本文介绍了在秒杀商品SKU表中使用乐观锁和MybatisPlus配置乐观锁的方法,并分析了测试环境和生产环境的隔离级别对乐观锁的影响,通过简单验证,... 目录一、场景分析 二、简单验证 2.1、可重复读 2.2、读已提交 三、最佳实践 3.1、配置重试模板

Spring中@Lazy注解的使用技巧与实例解析

《Spring中@Lazy注解的使用技巧与实例解析》@Lazy注解在Spring框架中用于延迟Bean的初始化,优化应用启动性能,它不仅适用于@Bean和@Component,还可以用于注入点,通过将... 目录一、@Lazy注解的作用(一)延迟Bean的初始化(二)与@Autowired结合使用二、实例解