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版本,并适配其他依赖
相关推荐
2601_959986241 小时前
M4Markets:把工具可用性做到位——逻辑梳理与提示整理
大数据·人工智能
薛定猫AI2 小时前
Codex 与 Claude Code 安装配置完全指南
大数据·人工智能·架构
SelectDB2 小时前
从 Machine-Readable 到 Agent-Ready:面向智能体的数据库接口演进
大数据·数据库·agent
前沿AI2 小时前
AI营销服一体化方案亮相2026中国汽车经销商大会,助力汽车销售全链路提效
大数据·人工智能·汽车
KaMeidebaby3 小时前
卡梅德生物技术快报|peg 修饰调控 MXene/WS2 异质结,氨气传感器制备与机理研究
大数据·前端·人工智能·架构·spark·新浪微博
ydyd202604213 小时前
设备管理应用推荐2026深度测评!
大数据·人工智能·机器学习
志栋智能3 小时前
超自动化巡检:降低运维总成本(TCO)的有效路径
大数据·运维·网络·人工智能·自动化
LONGZETECH3 小时前
软硬协同+故障注入:无人机仿真维修与操控仿真底层算法逻辑拆解
大数据·c语言·算法·3d·unity·无人机
码农小白AI3 小时前
AI报告审核与IACheck:自动化检测全面铺开后,为什么报告审核反而成了新的效率瓶颈?
大数据·人工智能·自动化
数智顾问3 小时前
(133页PPT)数据中心基础设施规划设计(附下载方式)
大数据·数据库·人工智能