草庐IT

如何使用Spring Cloud搭建高可用的Elasticsearch集群?详解Elasticsearch的安装与配置及Spring Boot集成的实现

陈书予 2023-04-24 原文

Spring Cloud 是一个基于 Spring Boot 的微服务框架,它提供了一系列组件和工具,方便开发人员快速搭建和管理分布式系统。Elasticsearch 是一个开源的全文搜索引擎,也是一个分布式、高可用的 NoSQL 数据库。本篇博客将详细讲解如何使用 Spring Cloud 搭建 Elasticsearch,并介绍如何在 Spring Cloud 微服务中使用 Elasticsearch 进行数据存储和检索。

目录

一、Elasticsearch 简介

二、Spring Cloud 简介

三、Spring Cloud 搭建 Elasticsearch

3.1安装 Elasticsearch

3.2 使用 Spring Boot 集成 Elasticsearch

4.使用 Spring Cloud 搭建 Elasticsearch

4.1 搭建微服务架构

4.2 集成 Elasticsearch

4.2.1 添加 Elasticsearch 依赖

4.2.2 添加 Elasticsearch 配置

4.2.3 使用 Elasticsearch

补充:

为了更好地使用Elasticsearch,我们可以使用官方提供的高级客户端工具包。

准备工作

添加依赖

配置Elasticsearch客户端

使用Elasticsearch客户端

总结


一、Elasticsearch 简介

Elasticsearch 是一个基于 Lucene 的分布式搜索引擎,它提供了实时分析、搜索、建议和聚合功能。它能够快速地存储、搜索和分析大量结构化和非结构化数据,并且具有高可用性和可伸缩性。Elasticsearch 提供了一个 RESTful API,可以通过 HTTP 协议进行访问和操作。

二、Spring Cloud 简介

Spring Cloud 是基于 Spring Boot 的微服务框架,它提供了一系列组件和工具,包括服务注册与发现、配置管理、负载均衡、熔断器、分布式追踪等,可以快速搭建和管理分布式系统。Spring Cloud 支持多种开源组件,包括 Netflix OSS、Consul、Zookeeper、Eureka 等。

三、Spring Cloud 搭建 Elasticsearch

在 Spring Cloud 微服务中使用 Elasticsearch,需要先进行 Elasticsearch 的安装和配置。下面将介绍如何在 Windows 环境下安装 Elasticsearch。

3.1安装 Elasticsearch

首先需要从 Elasticsearch 官网下载 Elasticsearch 的安装包,下载地址为:https://www.elastic.co/downloads/elasticsearch。选择对应的操作系统版本进行下载,本文以 Windows 10 为例。

下载完成后,解压缩安装包,进入解压后的文件夹,找到 bin 目录下的 elasticsearch.bat 文件,双击运行该文件。在启动 Elasticsearch 之前,需要先修改一些配置。打开 config 目录下的 elasticsearch.yml 文件,修改以下几个配置:

cluster.name: my-application
node.name: node-1
path.data: D:\elasticsearch\data
path.logs: D:\elasticsearch\logs

其中,cluster.name 表示集群的名称,可以自定义;node.name 表示节点的名称,也可以自定义;path.data 和 path.logs 分别表示 Elasticsearch 数据和日志的存储路径。

修改完成后,保存并关闭 elasticsearch.yml 文件。然后再次双击运行 elasticsearch.bat 文件,等待 Elasticsearch 启动完成。启动成功后,在浏览器中输入 http://localhost:9200/,可以看到 Elasticsearch 的基本信息。


3.2 使用 Spring Boot 集成 Elasticsearch

使用 Spring Boot 集成 Elasticsearch,需要添加 Elasticsearch 的依赖。在 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

添加依赖后,需要在 application.yml 文件中配置 Elasticsearch 的连接信息,如下所示:

spring:
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: localhost:9300

其中,cluster-name 和上面在 Elasticsearch 中配置的 cluster.name 相对应,cluster-nodes 表示 Elasticsearch 的节点地址和端口号。

使用 Spring Data Elasticsearch,可以很方便地进行数据的增删改查操作。只需要定义一个实体类,并继承 ElasticsearchRepository 接口即可。例如,定义一个 Book 实体类:

@Document(indexName = "book")
public class Book {
    @Id
    private String id;
    private String title;
    private String author;
    // getter 和 setter 方法省略
}

其中,@Document 注解用于指定 Elasticsearch 中的索引名称,@Id 注解用于指定实体类中的 ID 属性。

定义完实体类后,可以在其对应的 Repository 接口中定义增删改查方法,例如:

public interface BookRepository extends ElasticsearchRepository<Book, String> {
    List<Book> findByTitle(String title);
    List<Book> findByAuthor(String author);
}

这样就可以通过调用 BookRepository 中的方法进行数据的增删改查操作了。


4.使用 Spring Cloud 搭建 Elasticsearch

在 Spring Cloud 微服务中使用 Elasticsearch,需要先搭建一个基于 Spring Cloud 的微服务架构。本文将以 Spring Cloud Eureka 作为服务注册中心,Spring Cloud Config 作为配置中心,Spring Cloud Gateway 作为网关,Spring Cloud Feign 作为服务调用客户端,演示如何搭建一个微服务架构,并在其中使用 Elasticsearch 进行数据存储和检索。

4.1 搭建微服务架构

首先需要创建一个 Spring Boot 项目,作为微服务架构的父项目,命名为 spring-cloud-demo。在该项目的 pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

这些依赖分别是 Spring Cloud Eureka、Spring Cloud Config、Spring Cloud Gateway 和 Spring Cloud Feign。

在项目的 application.yml 文件中配置 Eureka、Config 和 Gateway 的相关信息,如下所示:

spring:
  application:
    name: spring-cloud-demo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    instance-id: ${spring.application.name}:${random.value}
    prefer-ip-address: true
server:
  port: 8000
---
spring:
  profiles

4.2 集成 Elasticsearch

在 Spring Cloud 微服务架构中集成 Elasticsearch,需要分别在每个微服务中添加 Elasticsearch 的相关依赖和配置。

4.2.1 添加 Elasticsearch 依赖

在微服务的 pom.xml 文件中添加 Elasticsearch 的相关依赖,如下所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.7.0</version>
</dependency>

其中,spring-boot-starter-data-elasticsearch 依赖用于集成 Spring Data Elasticsearch,elasticsearch-rest-high-level-client 依赖用于连接 Elasticsearch 服务器。

4.2.2 添加 Elasticsearch 配置

在微服务的 application.yml 文件中添加 Elasticsearch 的连接配置,如下所示:

spring:
  data:
    elasticsearch:
      cluster-name: my-application
      cluster-nodes: localhost:9300

其中,cluster-name 和 Elasticsearch 中配置的 cluster.name 相对应,cluster-nodes 表示 Elasticsearch 的节点地址和端口号。

4.2.3 使用 Elasticsearch

使用 Spring Data Elasticsearch 进行数据的增删改查操作和使用普通的 Spring Data JPA 操作类似,只需要定义一个实体类,并继承 ElasticsearchRepository 接口即可。例如,在一个微服务中定义一个 Book 实体类和对应的 Repository 接口,如下所示:

@Document(indexName = "book")
public class Book {
    @Id
    private String id;
    private String title;
    private String author;
    // getter 和 setter 方法省略
}

public interface BookRepository extends ElasticsearchRepository<Book, String> {
    List<Book> findByTitle(String title);
    List<Book> findByAuthor(String author);
}

其中,@Document 注解用于指定 Elasticsearch 中的索引名称,@Id 注解用于指定实体类中的 ID 属性。

定义完实体类和 Repository 接口后,就可以在服务中使用 BookRepository 中的方法进行数据的增删改查操作了。


补充:

为了更好地使用Elasticsearch,我们也可以使用官方提供的高级客户端工具包。

准备工作

在开始使用Elasticsearch高级客户端工具包之前,我们需要安装并启动Elasticsearch服务器。官方网站提供了安装包和文档,你可以按照文档的步骤进行安装和配置。

添加依赖

为了在Spring Boot和Spring Cloud项目中使用Elasticsearch高级客户端工具包,我们需要在项目中添加相关依赖。在Maven项目中,我们可以添加以下依赖:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.15.2</version>
</dependency>

在Gradle项目中,我们可以添加以下依赖:

implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.15.2'

配置Elasticsearch客户端

接下来,我们需要在Spring Boot和Spring Cloud项目中配置Elasticsearch客户端。我们可以通过以下方式来创建客户端:

@Bean
public RestHighLevelClient restHighLevelClient() {
    RestClientBuilder builder = RestClient.builder(
            new HttpHost("localhost", 9200, "http"),
            new HttpHost("localhost", 9201, "http"));
    return new RestHighLevelClient(builder);
}

在这个例子中,我们创建了一个RestHighLevelClient实例,并使用了两个HttpHost实例来指定Elasticsearch服务器的地址和端口。如果有多个服务器,我们可以通过添加多个HttpHost实例来指定它们的地址和端口。

使用Elasticsearch客户端

现在我们已经成功地配置了Elasticsearch客户端,我们可以使用它来进行数据操作。以下是一个简单的例子:

@Autowired
private RestHighLevelClient restHighLevelClient;

public void saveDocument() throws IOException {
    IndexRequest indexRequest = new IndexRequest("posts");
    indexRequest.id("1");
    indexRequest.source("title", "Spring Boot",
            "body", "Spring Boot is awesome!");

    IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

    System.out.println("Index Response: " + indexResponse);
}

在这个例子中,我们创建了一个IndexRequest实例,并指定了文档的id、索引名称和字段值。然后我们使用RestHighLevelClient实例来执行索引操作,并得到IndexResponse实例作为结果。


总结

本文介绍了如何使用 Spring Cloud 搭建一个微服务架构,并在其中使用 Elasticsearch 进行数据存储和检索。具体来说,主要分为以下几个步骤:

  1. 在 Elasticsearch 中创建索引和文档类型;
  2. 在 Spring Boot 项目中添加 Elasticsearch 的相关依赖,并配置连接信息;
  3. 使用 Spring Data Elasticsearch 进行数据的增删改查操作;
  4. 在 Spring Cloud 微服务架构中添加 Elasticsearch 的相关依赖和配置;
  5. 在微服务中使用 Spring Data Elasticsearch 进行数据的增删改查操作。

通过本文的介绍,相信读者已经掌握了如何在 Spring Boot 和 Spring Cloud 微服务架构中使用 Elasticsearch 进行数据存储和检索的方法。在实际开发中,还需要根据具体的需求和业务场景进行相应的调整和优化,以实现更好的效果

有关如何使用Spring Cloud搭建高可用的Elasticsearch集群?详解Elasticsearch的安装与配置及Spring Boot集成的实现的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐