1 maven依赖
点击查看代码
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2 application.yml
spring:
data:
elasticsearch:
# (注意:需要在es项目启动前,修改配置文件elasticsearch.yml中的cluster-name属性,配置文件中默认这个属性是不配置的,否则在启动本项目时会报错)
cluster-name: myes # 集群名称
cluster-nodes: 192.168.170.128:9300 # 地址
3 实体类层
点击查看代码
package com.rain.entity;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "mytest", type = "user")
@Data
public class UserEntity {
@Id
private String id;
private String name;
private Integer age;
private Integer sex;
}
4 Dao层
点击查看代码
package com.rain.repository;
import com.rain.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;
public interface UserDao extends CrudRepository<UserEntity, String> {
}
5 Controller层
点击查看代码
package com.rain.controller;
import com.rain.entity.UserEntity;
import com.rain.repository.UserDao;
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 ESController {
@Autowired
private UserDao userDao;
// 添加文档
@RequestMapping("/addUser")
public void addUser(@RequestBody UserEntity userEntity){
userDao.save(userEntity);
}
// 查询文档
public Optional<UserEntity> findById(String id){
return userDao.findById(id);
}
}
6 启动项目类
点击查看代码
package com.rain; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.rain.repository")
public class ESApplication {
public static void main(String[] args) {
SpringApplication.run(ESApplication.class);
}
}
7 报错解决
以下错误:
None of the configured nodes are available:
解决方案:
Vi /usr/local/elasticsearch-6.4.3/config/elasticsearch.yml
cluster.name: myes