在之前的文章 “Elasticsearch:通過 Spring Boot 創建 REST APIs 來訪問 Elasticsearch”,我詳細描述了如何在 Spring Boot 應用中使用 elasticsearch-rest-high-level-client 庫來和 Elasticsearch 來進行連接,在今天的文章中,我將使用另外一個庫 spring-boot-starter-data-elasticsearch 來和 Elasticsearch 進行連接,這種方法非常簡單直接,
為了方便大家閱讀,我把最終的代碼放到 github GitHub - liu-xiao-guo/SpringBootElasticsearch-demo,你可以使用如下的方式來獲得:
git clone https://github.com/liu-xiao-guo/SpringBootElasticsearch-demo
代碼解釋
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liuxg</groupId>
<artifactId>SpringBootElasticsearch-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootElasticsearch-demo</name>
<description>SpringBootElasticsearch-demo</description>
<properties>
<java.version>1.8</java.version>
<elastic.version>7.15.0</elastic.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<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>${elastic.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${elastic.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elastic.version}</version><!--$NO-MVN-MAN-VER$-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
在上面,請注意我們需要 dependency spring-boot-starter-data-elasticsearch,在我的 Elasticsearch 的集群中,我啟動了 Basic 安全認證,超級用戶 elastic 的密碼設定為 password,在應用中,我們有通過 RestHighLevelClient 來進行鑒權,所以,我也把 elasticsearch-rest-high-level-client 引入進來了,
組態檔
由于默認的埠地址 8080 和我的電腦的埠有沖突,我使用了 9999 埠,另外,我們也可以配置 Elasticsearch 的地址及埠,同時我們也定義了超級用戶 elastic 的密碼 password:
application.properties
server.port = 9999
elasticsearch.url=localhost:9200
elasticsearch.username=elastic
elasticsearch.password=password
document
Employee.java
package com.liuxg.springbootelasticsearchdemo.document;
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 = "employees", shards = 1, replicas = 0, refreshInterval = "5s")
public class Employee {
@Id
@Field(type = FieldType.Keyword)
private String id;
@Field(type = FieldType.Text)
private String name;
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
在上面,我們定義了索引的名稱 employees,它里面含有兩個欄位 id 及 name,它們的屬性分別是 keyword 及 text, 當我們運行 Spring Boot 應用時,它將會在 Elasticsearch 中自動幫我們生產 employees 這個索引,
Repository
EmployeeRepository.java
import com.liuxg.springbootelasticsearchdemo.document.Employee;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface EmployeeRepository extends ElasticsearchRepository<Employee, String> {
List<Employee> findAllByName(String name);
@Query("{\"match\":{\"name\":\"?0\"}}")
List<Employee> findAllByNameUsingAnnotations(String name);
}
在這里,我們定了如何訪問 Elasticsearch,其中 ElasticsearchRepository 里含有許多已經設計好的方法可以供我們使用,
Service
EmployeeService.java
package com.liuxg.springbootelasticsearchdemo.service;
import com.liuxg.springbootelasticsearchdemo.document.Employee;
import com.liuxg.springbootelasticsearchdemo.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
private final EmployeeRepository repository;
@Autowired
public EmployeeService(EmployeeRepository repository) {
this.repository = repository;
}
public void save(final Employee employee) { repository.save(employee); }
public Employee findById(final String id) { return repository.findById(id).orElse(null); }
public List<Employee> findByName(final String name) { return repository.findAllByName(name);}
public List<Employee> getEmployeesByNameUsingAnnotation(String name) {
return repository.findAllByNameUsingAnnotations(name);
}
public void deleteEmployee(String id) {
repository.deleteById(id);
}
}
Controller
EmployeeController.java
package com.liuxg.springbootelasticsearchdemo.controller;
import com.liuxg.springbootelasticsearchdemo.document.Employee;
import com.liuxg.springbootelasticsearchdemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
private final EmployeeService service;
@Autowired
public EmployeeController(EmployeeService service) {
this.service = service;
}
@PostMapping
public void save(@RequestBody final Employee employee) {
service.save(employee);
}
@GetMapping("/{id}")
public Employee findById(@PathVariable final String id) {
return service.findById(id);
}
@DeleteMapping("/{id}")
public boolean deleteById(@PathVariable String id) {
service.deleteEmployee(id);
return true;
}
@GetMapping("/name/{name}")
public List<Employee> findAllByName(@PathVariable String name) {
return service.findByName(name);
}
@GetMapping("/name/{name}/annotations")
public List<Employee> findAllByNameAnnotations(@PathVariable String name) {
return service.getEmployeesByNameUsingAnnotation(name);
}
}
這里定義了一些 REST 介面以方便我們訪問 Elasticsearch,
Configuration
Config.java
package com.liuxg.springbootelasticsearchdemo.configuration;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.liuxg.springbootelasticsearchdemo.repository")
@ComponentScan(basePackages = {"com.liuxg.springbootelasticsearchdemo"})
@RequiredArgsConstructor
public class Config extends AbstractElasticsearchConfiguration {
@Value("${elasticsearch.url}")
public String elasticsearchUrl;
@Value("${elasticsearch.username}")
public String elasticsearchUsername;
@Value("${elasticsearch.password}")
public String elasticsearchPassword;
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(elasticsearchUrl)
.withBasicAuth(elasticsearchUsername, elasticsearchPassword)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
在這里,我們使用了 application.properties 里的配置引數來建立和 Elasticsearch 的連接,并回傳一個 RestHighLevelClient,它的使用可以參閱我之前的文章 “Elasticsearch:通過 Spring Boot 創建 REST APIs 來訪問 Elasticsearch”,在本示例中,它僅被使用為鑒權,
Spring Boot Application
SpringBootElasticsearchDemoApplication.java
package com.liuxg.springbootelasticsearchdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootElasticsearchDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootElasticsearchDemoApplication.class, args);
}
}
整個代碼的結構如下:
$ tree
.
├── README.md
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── liuxg
│ │ └── springbootelasticsearchdemo
│ │ ├── SpringBootElasticsearchDemoApplication.java
│ │ ├── configuration
│ │ │ └── Config.java
│ │ ├── controller
│ │ │ └── EmployeeController.java
│ │ ├── document
│ │ │ └── Employee.java
│ │ ├── repository
│ │ │ └── EmployeeRepository.java
│ │ └── service
│ │ └── EmployeeService.java
│ └── resources
│ ├── application.properties
│ ├── static
│ └── templates
└── test
└── java
└── com
└── liuxg
└── springbootelasticsearchdemo
└── SpringBootElasticsearchDemoApplicationTests.java
測驗應用
我們編譯好應用,并運行起來,在本次測驗中,我將使用 Postman 來做為 REST 介面的測驗工具,
查看被創建的索引
在參考啟動后,它會自動幫我們創建一個叫做 employees 的索引,我們可以在瀏覽器中打入如下的地址:
http://localhost:9200/_cat/indices

從上面,我們可以看出來已經被創建的 employees 索引,我們還可以通過如下的方式來進行搜索:
http://localhost:9200/employees/_search
從上面的回傳結果看出來,employees 里沒有任何的資料, 如果在你的瀏覽器中不是以這種非常好看的縮進格式顯示的結果,建議你可以安裝 JSON formatter 插件,
接下來,我們通過 Spring Boot 的 API 介面來發送請求,并保存資料,

在上面,我們通過介面 http://localhost:9999/api/employee 向 Elasticsearch 發送一個如下的資料:
{
"id": "1",
"name": "liuxg"
}
這個資料的結構就是我們之前在 document 里定義的格式,我們再次通過瀏覽器來查看資料:
http://localhost:9200/employees/_search
我們可以看到如下的結果:

從上面我們可以看出來已經有一個資料被寫入進去了,
接下來,我們使用如下的介面來獲取剛剛寫入的這個資料:
http://localhost:9999/api/employee/1

可以看出來,我們的介面是作業正常的,
我們還可以通過搜索 name 來查詢一個檔案:
http://localhost:9999/api/employee/name/liuxg

我們也可以通過 annotations 來進行查詢:
http://localhost:9999/api/employee/name/liuxg/annotations

最后,我們也可以通過 API 來洗掉已經創建的檔案:
http://localhost:9999/api/employee/1

我們再通過瀏覽器來查詢 employees 的資料:

從上面,我們可以看出來之前創建的檔案已經被成功地洗掉了,
參考:
【1】Getting Started With Elasticsearch in Java Spring Boot
【2】Introduction into Spring Data Elasticsearch
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/330153.html
標籤:其他
上一篇:Hadoop的HA原理
