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

相关推荐
pq21731 分钟前
Spring FactoryBean源码解析
java·spring boot·spring
azhou的代码园2 小时前
基于SpringBoot+Vue的家教小程序
vue.js·spring boot·小程序·毕业设计·家教小程序
彭于晏Yan2 小时前
Spring Boot 聚合MongoDB查询
spring boot·后端·mongodb
逸Y 仙X3 小时前
文章二十六:ElasticSearch 异步查询执行重度任务
java·大数据·linux·运维·elasticsearch·搜索引擎·全文检索
MZ_ZXD0015 小时前
springboot音乐播放器系统-计算机毕业设计源码76317
java·c语言·c++·spring boot·python·flask·php
azhou的代码园5 小时前
基于微信小程序的图片识别科普系统的设计与实现
vue.js·spring boot·微信小程序·小程序·毕业设计·科普·图片识别
Filwaod6 小时前
互联网大厂Java面试实战:Spring+Redis+MySQL+JVM场景问答深度解析
jvm·spring boot·redis·mysql·java面试·技术面试·互联网大厂
安当加密6 小时前
Spring Boot应用接入国产安当凭据管理系统SMS Starter实战(附源码)
java·spring boot·后端
Filwaod7 小时前
Java面试现场:从Redis缓存到分布式事务,水货程序员李四的‘表演‘
java·jvm·spring boot·redis·mysql·面试·多线程
Filwaod7 小时前
互联网大厂Java面试实战:从Spring Boot到AI智能客服,水货程序员李四的翻车现场
spring boot·redis·mysql·spring cloud·微服务·ai·java面试