SpringBoot整合Elasticseach快速入门
SpringBoot整合Elasticseach快速入门
一、 Eclipse创建maven项目或导入一个Springboot项目
工具:
a.在官网下载解压缩ElasticSearch(版本同于maven dependencies下elasticsearch.jar的)
b.安装Postman客户端或谷歌浏览Postman插件
一、Eclipse创建maven项目或导入一个Springboot项目
1-1 项目结构图
1.修改pom.xml文件
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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>
<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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
2.修改App.java
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
3.entity包下创建Employee.java
@Document(indexName = "index", type = "employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String firstName;
private String lastName;
private Integer age = 0;
private String about;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
}
4.dao包下创建EmployeeRepository .java
@Component
public interface EmployeeRepository extends ElasticsearchRepository<Employee, String> {
/**
* 根据id获取员工信息
*
* @param id 员工id
* @return {@link Employee}员工信息,不存在返回<code>null</code>
*/
Employee queryEmployeeById(String id);
}
5.controller包下创建EsController .java
@RestController
@RequestMapping("/es")
public class EsController {
private final EmployeeRepository employeeRepository;
@Autowired
public EsController(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
@RequestMapping("/add/{id}")
public String addEmployee(@PathVariable String id) {
Employee employee = new Employee();
employee.setId(id);
employee.setAbout("about" + id);
employee.setAge(18);
employee.setFirstName("F");
employee.setLastName("L");
employeeRepository.save(employee);
System.out.println("add a employee: " + id);
return "success";
}
@RequestMapping("/delete/{id}")
public boolean deleteEmployee(@PathVariable String id) {
employeeRepository.deleteById(id);
return true;
}
@RequestMapping("/update/{id}")
public boolean updateEmployee(@PathVariable String id) {
Employee employee = employeeRepository.queryEmployeeById(id);
employee.setFirstName("modify" + id);
employeeRepository.save(employee);
System.out.println("update employee: " + id);
return true;
}
@RequestMapping("/query/{id}")
public Employee queryEmplyee(@PathVariable String id) {
Employee employee = employeeRepository.queryEmployeeById(id);
return employee;
}
}
6.创建resources目录并在其下创建application.properties
server.port=8080
spring.data.elasticsearch.cluster-nodes=你的IP:9300
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.local=false
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=60s
spring.data.elasticsearch.repositories.enable=true
二、elasticsearch下载与操作
1.在elastic官网(https://www.elastic.co)下载压缩包并解压;
2.找到config目录下elasticsearch.yml,取消cluster.name、node.name、network.host、http.port的注释,并修改为:
cluster.name: elasticsearch
node.name: "Franz Kafka"
network.host: 你的IP
http.port: 9200
3.bin目录下启动或使用cmd启动elasticsearch.bat。 浏览器或postman输入http://你的IP:9200/ 进行测试,正常显示的例子如下:
1.首先启动elasticsearch.bat
2.其次通过APP.java启动springboot-es-demo项目,成功启动后,elasticsearch端显示“[test-index] creating index”等信息,证明elasticsearch与项目通信成功。
3.Elasticsearch插入数据:
Postman输入http://localhost:8080/es/add/1,可观察到elasticsearch端显示“create_mapping [employee]”等信息。(同理可进行删除、更新、查询)
4.Elasticsearch查询数据:
Postman输入http://你的IP:9200/test-index/employee/_search?pretty,查询出test-index为索引,employee为type的数据如图所示。
三、可能会遇到的问题
1. 2019-06-0614:43:46.463WARN12768---[ient_boss][T#1]] o.e.transport.netty4.Netty4Transport : exception caught on transport layer [[id: 0x6e51abaf, L:/127.0.0.1:53426 - R:localhost/127.0.0.1:9300]], closing connection
java.io.IOException: Invalid string; unexpected character: 253 hex: fd
解决:localhost对应的ip为127.0.0.1,application.properties中cluster-nodes的ip和elasticsearch.yml的network.host的换为IPv4地址即可。
2.2019-06-06 11:47:08.887 ERROR 18024 --- [main] .d.e.r.s.AbstractElasticsearchRepository : failed to load elasticsearch nodes : org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{KJxLfl0PR46FnXjVL1wUcA}{99.1.237.253}{99.1.237.253:9300}]
原因:spring data elasticSearch 的版本与Elasticsearch版本不匹配。此项目中maven dependencies 下elasticsearch.jar版本为5.6.10,启动版本1.7.2与1.5.2的elasticsearch.bat皆报错,换用版本5.6.10的即可解决问题。