springboot整合es7.4
时间: 2023-10-30 22:09:46 浏览: 102
Spring Boot是一个快速开发框架,可以轻松地将Elasticsearch集成到你的应用程序中。下面是整合Spring Boot和Elasticsearch 7.4的步骤:
1. 在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 在application.properties文件中添加以下配置:
```
spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9300
```
3. 创建一个ElasticsearchRepository接口,用于定义Elasticsearch的操作方法。例如:
```
public interface BookRepository extends ElasticsearchRepository<Book, String> {
List<Book> findByTitle(String title);
}
```
4. 创建一个Elasticsearch的配置类,用于配置Elasticsearch的客户端。例如:
```
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient client() {
RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
@Bean
public ElasticsearchRestTemplate elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client());
}
}
```
5. 在你的代码中使用ElasticsearchRepository接口中定义的方法来操作Elasticsearch。例如:
```
@Autowired
private BookRepository bookRepository;
public void searchBooks() {
List<Book> books = bookRepository.findByTitle("Spring Boot");
// do something with the books
}
```
阅读全文