Elasticsearch8搭建及Springboot中集成使用
以下是一个简化的Spring Boot项目中集成Elasticsearch 8的例子:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- 添加Spring Boot的Elasticsearch依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 添加Spring Boot的测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 在
application.properties
或application.yml
中配置Elasticsearch信息:
# application.properties
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.elasticsearch.rest.uris=http://localhost:9200
- 创建一个实体类来映射Elasticsearch中的文档:
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = "sampleindex")
public class SampleEntity {
@Id
private String id;
private String content;
// 省略getter和setter方法
}
- 创建一个Elasticsearch仓库接口:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface SampleEntityRepository extends ElasticsearchRepository<SampleEntity, String> {
// 可以添加自定义查询方法
}
- 创建一个服务类使用仓库:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SampleEntityService {
@Autowired
private SampleEntityRepository repository;
public List<SampleEntity> findAll() {
return repository.findAll();
}
// 其他业务方法
}
- 创建一个控制器类来提供API接口:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class SampleEntityController {
@Autowired
private SampleEntityService service;
@GetMapping("/entities")
public List<SampleEntity> getAllEntities() {
return service.findAll();
}
}
- 创建一个启动类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ElasticsearchDemoApplication {
public static voi
评论已关闭