springboot使用ssl连接elasticsearch

使用es时ssl证书报错 unable to find valid certification path to requested target

1.依赖

bash 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2.配置证书

ssl证书转换

bash 复制代码
keytool -import -alias mycert -file mycert.cer -keystore mytruststore.jks -storepass mytruststorepassword

application.yaml配置

bash 复制代码
spring:  
  elasticsearch:
    key-store: classpath:ssl/truststore.jks
    key-store-password: test123..
    username: admin
    password: xxx
    #不用带协议
    uris: xxxxx:9200

配置类

bash 复制代码
package com.echosell.spider.appspider.config;

import com.echosell.spider.appspider.entity.properties.EsProperties;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * @author 张子一
 * @project echosell-spider
 * @description es配置
 * @date 2025年01月20日*
 */
@Configuration
@Slf4j
public class ElasticsearchTemplateConfig {

    @Autowired
    EsProperties esProperties;
    @Autowired
    ResourceLoader resourceLoader;

    @Bean
    public RestHighLevelClient restHighLevelClient() throws Exception {
        ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo(esProperties.getUris())
                .usingSsl(createSSLContext(esProperties.getKeyStore(), esProperties.getKeyStorePassword()))
                .withBasicAuth(esProperties.getUsername(), esProperties.getPassword())
                .build();
        return RestClients.create(clientConfiguration).rest();
    }

    @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate(RestHighLevelClient restHighLevelClient){
        return new ElasticsearchRestTemplate(restHighLevelClient);
    }




    private SSLContext createSSLContext(String keyStorePath, String keyStorePassword) throws Exception {
//        // 加载密钥库
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = resourceLoader.getResource(keyStorePath);
        // 读取文件内容...
        try (FileInputStream fileInputStream = new FileInputStream(resource.getFile())) {
            trustStore.load(fileInputStream, keyStorePassword.toCharArray());
        }

        // 创建信任管理器工厂
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        // 初始化 SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

        return sslContext;
    }

}

3.信任所有证书(无证书使用)

bash 复制代码
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new X509TrustManager() {
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}}, new SecureRandom());

直接使用ElasticsearchRestTemplate即可

4.介绍

网上百度无结果,查看了部分结果发现 RestHighLevelClient 使用的SSLContext,且默认使用的系统默认证书 ,将自己的证书导入 SSLContext,封装到RestHighLevelClient即可。

相关推荐
摇滚侠2 分钟前
《SpringBoot 3:入门与应用实战》第 14 章 打包与部署 Spring Boot 应用打包 阅读笔记 41
spring boot·笔记·后端
Elastic 中国社区官方博客8 分钟前
在 Elasticsearch 中回填时间序列数据:通过批量 API 加载数月的历史指标数据
大数据·运维·数据库·人工智能·elasticsearch·搜索引擎·全文检索
大梦想家a15 分钟前
新能源汽车共享充电桩收费管理系统的设计与实现(SpringBoot+MyBatis-Plus+Vue,前后台分离完整源码)
spring boot·汽车·mybatis
今夕资源网1 小时前
本地SSL证书生成工具本地 HTTPS 配置不用再敲命令:CertTool 一站式管理自签证书与 Hosts
网络协议·https·ssl·ssl证书生成·ssl本地测试证书
摇滚侠2 小时前
《SpringBoot 3:入门与应用实战》第 14 章 打包与部署 制作 Docker 镜像 阅读笔记 43
spring boot·笔记·docker
xiaoqiMikko4 小时前
七条 advisory 各给了一个修复版,而一次修完的那个数字一条都没写
java·spring boot
凯哥Java4 小时前
System.setProperty 的正确姿势:Spring Boot 启动类里的“缺省值“魔法
java·spring boot·后端
2401_861678624 小时前
Git 在 Windows 使用
windows·git·elasticsearch
ShineWinsu4 小时前
对于 Vue 3:开发前需要掌握的 JavaScript 核心基础:从变量、数组方法到 Promise、Async/Await 与 ES Module 的解析
javascript·vue.js·elasticsearch
Elasticsearch5 小时前
如何通过一条 ES|QL 查询为 Elasticsearch 中的每个指标构建指标图表
elasticsearch