0%

springboot中elasticsearch的集成与使用

Elasticsearch是一个开源、分布式、RESTful搜索和分析引擎。 Spring Boot为Elasticsearch提供基本的自动配置。

springboot支持多个http客户端:Java的“Low Level”(RestClient)and “High Level”(RestHighLevelClient)的rest客户端,以及Jest。同时,传输客户端也仍在Spring Data Elasticsearch中使用。

下面就来介绍一下spring boot如何通过 spring data使用elasticsearch。

如何安装elasticsearch?

引入依赖

首先是引入 Spring Data Elasticsearch的依赖,同时为了通过web接口断来测试,亦加入web的依赖。

1
2
3
4
5
6
7
8
9
10
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

es环境配置

在application.yml文件中写入es的配置,这里是以三个节点为例(需要说明的是,es默认的集群名字为elasticsearch,且一个节点也是集群)。

1
2
3
4
5
spring:
data:
elasticsearch:
cluster-name: elasticsearch-cluster
cluster-nodes: 127.0.0.1:9300,127.0.0.1:9301,177.0.0.1:9302

应用案例

这里通过一个简单的案例代码来介绍:用户信息的添加和查询。

实体PO

在po上,以@Document注解来标明存入的索引以及类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.lazycece.sbac.elasticsearch.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.annotations.Document;

import java.util.Date;

/**
* @author lazycece
* @date 2018/10/16
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "index", type = "doc")
public class User {

private String id;
private String username;
private String name;
private Integer age;
private Date createTime = new Date();
private Date updateTime = new Date();
}

po层代码

这里在po层用repository的形式进行交互,当然也可以选取用template形式交互。

1
2
3
4
5
6
7
8
9
10
11
12
package com.lazycece.sbac.elasticsearch.repository;

import com.lazycece.sbac.elasticsearch.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
* @author lazycece
* @date 2018/10/16
*/
public interface UserEsRepository extends ElasticsearchRepository<User,String> {
User findByUsername(String name);
}

接口层代码

这里通过简单的两个接口来应用es的查询和写入操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.lazycece.sbac.elasticsearch.controller;

import com.lazycece.sbac.elasticsearch.entity.User;
import com.lazycece.sbac.elasticsearch.repository.UserEsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
* @author lazycece
* @date 2018/10/16
*/
@RestController
@RequestMapping("/elasticsearch")
public class ElasticsearchDemoController {

private UserEsRepository userEsRepository;

@Autowired
public ElasticsearchDemoController(UserEsRepository userEsRepository) {
this.userEsRepository = userEsRepository;
}

@GetMapping("/demo")
public Object demo() {
return "welcome to elasticsearch cluster demo ...";
}

@PutMapping("/user/add")
public Object addUserInfo(User user) {
if (StringUtils.isEmpty(user.getName().trim())) {
return "add user fail: username is null ...";
}
User userFind = userEsRepository.findByUsername(user.getUsername());
if (userFind != null) {
return "add user fail: user exist";
}
userEsRepository.save(user);
return "add user success ...";
}

@GetMapping("/user/info")
public Object getUserInfo(@RequestParam String username) {
return userEsRepository.findByUsername(username);
}
}

单元测试验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.lazycece.sbac.elasticsearch.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ElasticsearchDemoControllerTest {

@Resource
private MockMvc mockMvc;


@Test
public void testAddUserInfo() throws Exception {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("username", "lazycece");
params.add("name", "W");
params.add("age", "99");
this.mockMvc.perform(
MockMvcRequestBuilders
.put("/elasticsearch/user/add")
.params(params))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}

@Test
public void testGetUserInfo() throws Exception {
this.mockMvc.perform(
MockMvcRequestBuilders
.get("/elasticsearch/user/info")
.param("username", "lazycece"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}

案例源码

案例源码地址:https://github.com/lazycece/springboot-actual-combat/tree/master/springboot-ac-elasticsearch