一、SpringBoot整合Elasticsearch
SpringBoot整合Elasticsearch非常简单,Elasticsearch实现了JPA接口,我们只需要引入Elasticsearch的Maven依赖,然后像使用JPA那样操作即可。
1. Maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Elasticsearch依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- lombok工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
application.yml 配置
spring:
data:
elasticsearch:
# 集群名称(默认名称elasticsearch, 可以在elasticsearch.yml文件中配置)
cluster-name: elasticsearch
# elasticsearch地址(注意:端口号为9300)
cluster-nodes: 192.168.2.104:9300
2. 实体类
package com.example.demo.entity;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* ES操作实体类
* indexName:索引名称
* type: 索引类型
*/
@Document(indexName = "myindex",type = "user")
@Data
public class UserEntity {
private String id;
private String name;
private Integer sex;
private Integer age;
}
3. DAO层(跟JPA操作一样)
package com.example.demo.repository;
import com.example.demo.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<UserEntity,String> {
}
5. Controller层
package com.example.demo.controller;
import com.example.demo.entity.UserEntity;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
/**
* 添加User
* @param user
* @return
*/
@RequestMapping("/addUser")
public UserEntity addUser(@RequestBody UserEntity user){
return userRepository.save(user);
}
/**
* 根据id查找user
* @param id
* @return
*/
@RequestMapping("/findUser")
public Optional<UserEntity> getUser(String id){
return userRepository.findById(id);
}
}
6. 启动类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@EnableElasticsearchRepositories(basePackages = "com.example.demo.repository") // 扫包
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
二、测试
添加用户接口 http://localhost:8080/addUser
获取用户接口 http://localhost:8080/findUser?id=2
是不是发现SpringBoot整合Elasticsearch超简单,soeasy ~~~