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即可。

相关推荐
元界metalite1 分钟前
SpringBoot修改接口全字段更新为什么危险-MetaLite如何只更新变化字段
spring boot
Devin~Y4 分钟前
从内容社区到AI智能客服:Spring Boot + Spring Cloud + Spring AI 全栈实战面试拆解
java·spring boot·redis·elasticsearch·spring cloud·kafka·mybatis
2602_9599609211 分钟前
电商大厂Java面试:从Spring Boot、JPA、微服务到Redis、Kafka、Spring Security与监控,谢飞机的爆笑三轮问答
java·jvm·spring boot·redis·面试题
码农进化录15 分钟前
Java 程序员的 AI 进化论 | Spring Boot 搭企业智能客服,从设计到上线
java·spring boot·openai
旺仔学长 哈哈17 分钟前
别只做车辆 CRUD:Spring Boot 共享汽车管理系统从预约到还车的完整实现---源码53766
java·spring boot·在线预约·共享汽车
weixin_BYSJ198720 分钟前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
weixin_BYSJ198730 分钟前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
YDS82941 分钟前
大营销平台 —— 第二阶段应用接口实现
java·spring boot·ddd
RuoyiOffice2 小时前
Springboot+WebSocket×场景×渠道:企业统一消息中心编排实战
spring boot·websocket·短信·消息中心·spring boot 3·站内信·场景编排
云烟成雨TD2 小时前
Micrometer 系列【67】统一观测:基于 Spring Boot 的生产级演示案例 | 跨线程场景
spring boot·云原生·链路追踪