SpringBoot项目实战_Elasticsearch实现 - 在SpringBoot项目中实现Elasticsearch,首先需要添加依赖
在SpringBoot项目中实现Elasticsearch,首先需要添加依赖。在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
接下来,需要在application.yml或application.properties文件中配置Elasticsearch的相关信息:
spring:
data:
elasticsearch:
url: http://localhost:9200
cluster-name: my-cluster
discovery:
enabled: true
register-with-eureka: false
namespace: my-namespace
然后,创建一个实体类,用于映射Elasticsearch中的文档:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "my_index")
public class MyEntity {
@Id
private String id;
private String name;
private int age;
// getter和setter方法
}
接下来,创建一个Service类,用于处理与Elasticsearch的交互:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service; 拼多多帮助力入口
@Service
public class MyService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public void save(MyEntity entity) {
elasticsearchTemplate.save(entity);
}
}
最后,创建一个Controller类,用于处理HTTP请求并调用Service进行操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class MyController {
@Autowired
private MyService myService;
@PostMapping("/save")
public void save(@RequestBody MyEntity entity) {
myService.save(entity);
}
}
这样,当有HTTP请求到达/save接口时,SpringBoot会自动将请求转发给MyService的save方法,并在Elasticsearch中保存对应的文档。