elasticsearch更换为opensearch

1.环境

  • springboot升级至3.x
  • jdk17
  • elasticsearch 7.1、opensearch 2.x

2. pom依赖

springboot版本

bash 复制代码
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.2</version>
        <relativePath/> 
    </parent>

opensearch依赖

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

若使用动态数据源版本跟随升级(2.x和3.x springboot的动态数据源依赖不一样)

bash 复制代码
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
            <version>4.2.0</version>

3. opensearchtemplate配置

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

import com.echosell.spider.appspider.entity.properties.OsProperties;
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.opensearch.client.RestClient;
import org.opensearch.client.RestHighLevelClient;
import org.opensearch.data.client.orhlc.OpenSearchRestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.repository.init.ResourceReader;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.concurrent.TimeUnit;


@Configuration
@Slf4j
public class OpenSearchTemplateConfig  {

    @Autowired
    ResourceLoader resourceLoader;

    @Bean
    public RestHighLevelClient restHighLevelClient(OsProperties osProperties) throws Exception {
        //解析hostlist配置信息
        String[] split = osProperties.getUris().split(",");
        //创建HttpHost数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for(int i=0;i<split.length;i++){
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        //创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray).setHttpClientConfigCallback(httpClientBuilder -> {

            httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
            httpClientBuilder.setMaxConnTotal(osProperties.getMaxConnTotal());
            httpClientBuilder.setConnectionTimeToLive(osProperties.getConnTimeToLive(), TimeUnit.SECONDS);
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(osProperties.getUsername(), osProperties.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            return httpClientBuilder;
        }));

//        ClientConfiguration.MaybeSecureClientConfigurationBuilder maybeSecureClientConfigurationBuilder = ClientConfiguration.builder().connectedTo(osProperties.getUris());
//        if(osProperties.getUseSsl()){
//            maybeSecureClientConfigurationBuilder.usingSsl(createSSLContext(osProperties.getKeyStore(), osProperties.getKeyStorePassword()));
//        }
//        maybeSecureClientConfigurationBuilder.withConnectTimeout(osProperties.getConnTimeToLive())
//                .withBasicAuth(osProperties.getUsername(), osProperties.getPassword())
//                .withSocketTimeout(osProperties.getConnectionTimeout())
//                .withClientConfigurer(clientConfigurer -> {
//                    return clientConfigurer;
//                });
//        return RestClients.create(maybeSecureClientConfigurationBuilder.build()).rest();

    }

    @Bean
    public OpenSearchRestTemplate openSearchRestTemplate(RestHighLevelClient restHighLevelClient){
        return new OpenSearchRestTemplate(restHighLevelClient);
    }




    private SSLContext createSSLContext(String keyStorePath, String keyStorePassword) throws Exception {
        // 加载密钥库
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        ClassLoader classLoader = ResourceReader.class.getClassLoader();
        // 读取文件内容...
        try (InputStream inputStream = classLoader.getResourceAsStream(keyStorePath)) {
            trustStore.load(inputStream, 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;
    }



}

4.notice

  • springboot 的opensearchtemplate依赖于elasticsearchtemplate,所以之前es的依赖需要保留。
  • opensearch的maven版本只适配springboot3.x。所以需要升级springboot版本,并适配其他依赖
相关推荐
hughnz1 天前
AI和自动化让油田钻工慢慢消失
大数据·人工智能
juniperhan1 天前
Flink 系列第8篇:Flink Checkpoint 全解析(原理+流程+配置+优化)
大数据·分布式·flink
GIS数据转换器1 天前
延凡低成本低空无人机AI巡检方案
大数据·人工智能·信息可视化·数据挖掘·无人机
七夜zippoe1 天前
OpenClaw 子代理(Subagent)机制详解
大数据·人工智能·subagent·openclaw·子代理
财经三剑客1 天前
长安汽车3月销量超27万辆 海外及新能源环比大幅增长
大数据·人工智能·汽车
ClouGence1 天前
不用搭复杂系统,也能做跨地域数据迁移?
大数据·数据库·saas
xixixi777771 天前
Token 经济引爆 AI 产业加速:从百模大战到百虾大战,谁在定义 2026 的中国 AI?
大数据·人工智能·机器学习·ai·大模型·算力·通信
Gent_倪1 天前
数据建模概念解析
大数据·数据建模
永霖光电_UVLED1 天前
Polar Light 获得了欧盟Eurostars计划的110万欧元(€1.1m)资助
大数据·人工智能·物联网·汽车·娱乐
琪伦的工具库1 天前
批量excel文件删除列工具使用说明:按列号或列名批量删除/保留,支持预览与大文件优化
大数据·excel