详解 Jeecg-boot 框架如何配置 elasticsearch
Jeecg-boot 框架支持集成 Elasticsearch 用于高效搜索。以下是配置和使用 Elasticsearch 的基本步骤:
- 添加依赖:在项目的
pom.xml
文件中添加 Elasticsearch 客户端的依赖。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.2</version>
</dependency>
- 配置 Elasticsearch:在
application.yml
或application.properties
文件中配置 Elasticsearch 的连接信息。
elasticsearch:
host: localhost
port: 9200
scheme: http
- 创建配置类:创建一个配置类来配置 Elasticsearch 客户端。
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticsearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Value("${elasticsearch.scheme}")
private String scheme;
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, scheme));
return new RestHighLevelClient(builder);
}
}
- 使用 Elasticsearch:在需要搜索的地方注入
RestHighLevelClient
实例,并使用它来执行搜索操作。
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class SearchService {
@Autowired
private RestHighLevelClient client;
public SearchResponse search(String index, String text) throws IOException {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("fieldname", text));
searchRequest.source(searchSourceBuilder);
return client.search(searchRequest, RequestOptions.DEFAULT);
}
}
确保在项目启动时创建 RestHighLevelClient
实例,并在不再需要时关闭它,以避免资源泄露。
以上步骤提供了一个基本的 Elasticsearch 集成示例。根据 Jeecg-boot 的具体需求,可能还需要进行额外配置,如实体映射、数据导入导出工具等。
评论已关闭