创建maven项目
添加pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.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>
添加配置文件
spring:
data:
elasticsearch:
####集群名称 需要和配置文件中的cluster-name一致
cluster-name: myes
####地址
cluster-nodes: 192.168.43.66:9300
ES 有两个端口一个是单机用 9200基于http协议,9300用于集群环境下基于tcp协议
这里 集群名称 需要和配置文件elasticsearch.yml中的cluster-name一致
cluster-name: myes 不然操作时候会报错
创建实体类
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import lombok.Data;
@Document(indexName="xuxu_index",type="user")
@Data
public class UserEntity {
@Id
private String id;
private String name;
private Integer age;
private String sex;
}
@Document(indexName="xuxu_index",type="user") 分别配置索引名称索引相当于数据库和类型 类型相当于表
创建数据访问层 UserDao接口继承CrudRepository接口 不需要写具体实现类,es已经实现 使用时直接调用即可
public interface UserDao extends CrudRepository<UserEntity, String>{
}
CrudRepository<UserEntity, String> 泛型中的String代表的是ID的类型
创建controller
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@RequestMapping("/addUser")
public UserEntity addUser(@RequestBody UserEntity userEntity) {
UserEntity user = userDao.save(userEntity);
return user;
}
@RequestMapping("/findUserById/{id}")
public Optional<UserEntity> findUserById(@PathVariable String id) {
Optional<UserEntity> user = userDao.findById(id);
return user;
}
}
启动 使用postman测试