【Spring】SpringBoot3+ES(Elasticsearch)の環境構築

发布时间 2023-12-04 17:09:25作者: 农民工024

参考URL:

https://blog.csdn.net/cicada_smile/article/details/132308849

https://www.cnblogs.com/hualess/p/11540477.html

Elasticsearchは、オープンソースの分散型検索エンジンであり、大量のデータをリアルタイムで検索、分析することができます。主にJavaで開発されており、Apache Luceneという検索エンジンライブラリをベースにしています。

Elasticsearchの主な特徴は以下の通りです。

  1. 分散型アーキテクチャ: Elasticsearchは、データを複数のノードに分散させることができるため、データの可用性とスケーラビリティが向上します。

  2. リアルタイム検索: Elasticsearchは、データのインデックス化が非常に高速であり、リアルタイムに検索が可能です。

  3. フルテキスト検索: Elasticsearchは、高度なフルテキスト検索機能を提供しており、検索クエリの柔軟性が高いです。

  4. RESTful API: Elasticsearchは、RESTful APIを通じてデータのインデックス化、検索、管理ができるため、様々なプログラミング言語やフレームワークと連携が容易です。

  5. スキーマレス: Elasticsearchは、JSON形式のドキュメントを扱うことができ、スキーマを事前に定義する必要がありません。

  6. 高度な分析機能: Elasticsearchは、データの集計や分析を行うための機能を提供しており、ビッグデータの解析に適しています。

Elasticsearchは、ログ分析、全文検索、データ可視化など、様々な用途で利用されており、Elastic Stack(以前はELK Stackと呼ばれていた)という一連の製品群とともに、幅広い分野で活用されています。Elastic Stackには、Elasticsearchのほかに、データ収集ツールのLogstash、データ可視化ツールのKibana、軽量データシッパーのBeatsが含まれています。

 

 ■ESの環境構築

ー>ダウンロードURL:<https://www.elastic.co/cn/downloads/elasticsearch> 

cluster.name: my-es

node.name: es_node

path.data: C:/elasticsearch-8.11.1/data

path.logs: C:/elasticsearch-8.11.1/logs

network.host: 0.0.0.0

http.port: 9200

# Enable security features
# xpack.security.enabled: false

xpack.security.enrollment.enabled: true

# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
  enabled: false
  keystore.path: certs/http.p12

# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12
# Create a new cluster with the current node only
# Additional nodes can still join the cluster later
cluster.initial_master_nodes: ["DESKTOP-3CEF7MJ"]

# Allow HTTP API connections from anywhere
# Connections are encrypted and require user authentication
http.host: 0.0.0.0
elasticsearch.yml

ー>命令:

①パスワードの再発行:elasticsearch-reset-password -u 用户名

②パスワードの変更:elasticsearch-reset-password --username 用户名 -i

③パスワードの任意作成:elasticsearch-reset-password --url "http://localhost:9200" --username 用户名 -i

④ー1ユーザの新規:elasticsearch-users useradd 用户名

④ー2役割の設定:elasticsearch-users roles -a superuser 用户名

④ー3ユーザのPWの変更:elasticsearch-users passwd 用户名

■SpringBoot配置

①POM.xmlにPluginを追加

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

②Entity対象を追加

package com.example.springelasticsearchsample.document;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "people")
public class Person {
    @Id
    private String id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(String id, String name, int age){
        this.id=id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
Person.java

③データの連結を追加

package com.example.springelasticsearchsample.repo;

import com.example.springelasticsearchsample.document.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface PersonRepository extends ElasticsearchRepository<Person,String> {
}

④サービスを追加

package com.example.springelasticsearchsample.service;

import com.example.springelasticsearchsample.document.Person;
import com.example.springelasticsearchsample.repo.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;

    public void saveTestData(List<Person> lst){
        for (Person person: lst){
            personRepository.save(person);
        }
    }

    public Person save(Person person){
        return personRepository.save(person);
    }

    public Person findById(String id){
        return personRepository.findById(id).orElse(null);
    }

}

⑤コントロールを追加

package com.example.springelasticsearchsample.controller;

import com.example.springelasticsearchsample.document.Person;
import com.example.springelasticsearchsample.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping("/index")
    public String index(){
        return "person";
    }


    @PostMapping("/test")
    public void saveTestData(){
        Person p1 = new Person("1","zhang3",20);
        Person p2 = new Person("2","li4",30);
        Person p3 = new Person("3","wang5",50);
        List<Person> peoplelst = Arrays.asList(p1,p2,p3);
        personService.saveTestData(peoplelst);
    }

    @PostMapping("/save")
    public Person save(@RequestBody Person book){
        return personService.save(book);
    }

    @GetMapping("/{id}")
    public Person getBookById(@PathVariable String id){
        return personService.findById(id);
    }
}

⑥実行APPを追加

package com.example.springelasticsearchsample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.example.springelasticsearchsample.repo"})
public class SpringElasticsearchSampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringElasticsearchSampleApplication.class, args);
    }

}

⑦YAMLを追加

server:
  port: 8080
  servlet:
    context-path: /es

spring:
  elasticsearch:
    uris: http://localhost:9200
    username: root
    password: password
  data:
    elasticsearch:
      cluster-name: my-es
      cluster-nodes: localhost:9200

■補足

ポイントの開放を設定

 

 ※:再起動が必要

==========================================

Spring BootとElasticsearchを使用した複雑なサンプルを示します。このサンプルでは、商品情報を検索するシンプルなE-commerceアプリケーションを作成します。

  1. まず、商品情報を表すProductクラスを作成します。このクラスには、商品ID、名前、説明、カテゴリ、価格、および在庫数が含まれます。
    import org.springframework.data.annotation.Id;
    import org.springframework.data.elasticsearch.annotations.Document;
    import org.springframework.data.elasticsearch.annotations.Field;
    import org.springframework.data.elasticsearch.annotations.FieldType;
    
    @Document(indexName = "products", type = "product")
    public class Product {
    
        @Id
        private String id;
    
        @Field(type = FieldType.Text)
        private String name;
    
        @Field(type = FieldType.Text)
        private String description;
    
        @Field(type = FieldType.Keyword)
        private String category;
    
        @Field(type = FieldType.Double)
        private double price;
    
        @Field(type = FieldType.Integer)
        private int stock;
    
        // getters and setters
    }
    View Code

 

  1. 次に、ProductRepositoryインターフェースを作成します。これは、Spring Data ElasticsearchのElasticsearchRepositoryインターフェースを拡張することで実現できます。
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    }
    View Code
  1. 商品情報を検索するためのサービスクラスProductServiceを作成します。このクラスでは、リポジトリインターフェースを使用して、Elasticsearchへのデータの追加、検索、更新、削除などの操作を行います。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class ProductService {
    
        @Autowired
        private ProductRepository productRepository;
    
        public Product save(Product product) {
            return productRepository.save(product);
        }
    
        public Product findById(String id) {
            return productRepository.findById(id).orElse(null);
        }
    
        public List<Product> findAll() {
            return (List<Product>) productRepository.findAll();
        }
    
        public void deleteById(String id) {
            productRepository.deleteById(id);
        }
    }
    View Code
  2. 最後に、商品情報を操作するためのRESTコントローラークラスProductControllerを作成します。このクラスでは、ProductServiceを使用して、商品情報の追加、検索、更新、削除を行うエンドポイントを提供します。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/api/products")
    public class ProductController {
    
        @Autowired
        private ProductService productService;
    
        @PostMapping
        public Product create(@RequestBody Product product) {
            return productService.save(product);
        }
    
        @GetMapping("/{id}")
        public Product getById(@PathVariable String id) {
            return productService.findById(id);
        }
    
        @GetMapping
        public List<Product> getAll() {
            return productService.findAll();
        }
    
        @PutMapping("/{id}")
        public Product update(@PathVariable String id, @RequestBody Product product) {
            Product existingProduct = productService.findById(id);
            if (existingProduct == null) {
                return null;
            }
            product.setId(id);
            return productService.save(product);
        }
    
        @DeleteMapping("/{id}")
        public void delete(@PathVariable String id) {
            productService.deleteById(id);
        }
    }
    View Code
  3. テストデータを追加するためのサンプルコードを示します。このコードでは、CommandLineRunnerインターフェースを実装したTestDataLoaderクラスを作成し、アプリケーションの起動時にテストデータをElasticsearchに追加します。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    import java.util.List;
    
    @Component
    public class TestDataLoader implements CommandLineRunner {
    
        @Autowired
        private ProductService productService;
    
        @Override
        public void run(String... args) throws Exception {
            loadTestData();
        }
    
        private void loadTestData() {
            List<Product> products = Arrays.asList(
                    new Product("1", "Product A", "This is product A", "Electronics", 100.0, 10),
                    new Product("2", "Product B", "This is product B", "Electronics", 200.0, 20),
                    new Product("3", "Product C", "This is product C", "Books", 50.0, 30),
                    new Product("4", "Product D", "This is product D", "Clothing", 30.0, 40),
                    new Product("5", "Product E", "This is product E", "Toys", 20.0, 50)
            );
    
            for (Product product : products) {
                productService.save(product);
            }
        }
    }
    View Code