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版本,并适配其他依赖
相关推荐
xixixi777771 小时前
基于零信任架构的通信
大数据·人工智能·架构·零信任·通信·个人隐私
Hello.Reader1 小时前
Flink 自适应批执行(Adaptive Batch Execution)让 Batch 作业“边跑边优化”
大数据·flink·batch
LaughingZhu3 小时前
Product Hunt 每日热榜 | 2026-01-31
大数据·人工智能·经验分享·搜索引擎·产品运营
babe小鑫3 小时前
中专学历进入快消大厂终端销售岗位的可行性分析
大数据
samFuB3 小时前
【工具变量】区县5A级旅游景区DID数据集(2000-2025年)
大数据
百夜﹍悠ゼ3 小时前
数据治理DataHub安装部署
大数据·数据治理
wdfk_prog4 小时前
解决 `git cherry-pick` 引入大量新文件的问题
大数据·git·elasticsearch
洛阳纸贵4 小时前
JAVA高级工程师--Elasticsearch
大数据·elasticsearch·搜索引擎
TracyCoder1234 小时前
ElasticSearch内存管理与操作系统(二):深入解析 Circuit Breakers(熔断器)机制
大数据·elasticsearch·搜索引擎
外参财观6 小时前
从浏览器到“超级眼”:夸克的突围战
大数据