欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

springboot配置Elasticsearch

时间:2023-04-16

版本说明 :
spring boot: 2.3.0.RELEASE
elasticsearch: 7.4.0
spring-cloud:Hoxton.SR10
spring-cloud-alibaba: 2.2.1.RELEASE

依赖

org.elasticsearch.client elasticsearch-rest-high-level-client ${elasticsearch-rest-client-version} org.elasticsearch elasticsearch org.elasticsearch.client elasticsearch-rest-client org.elasticsearch elasticsearch ${elasticsearch-rest-client-version} org.elasticsearch.client elasticsearch-rest-client ${elasticsearch-rest-client-version}

yaml配置

#es配置信息(自定义配置)es: hosts: 172.17.200.21 port: 9200 username: elastic password: rzS8OXXCm8Ez schema: http # 使用的协议 connectTimeOut: 1000 #连接超时时间 socketTimeOut: 30000 #连接超时时间 connectionRequestTimeOut: 500 #获取连接的超时时间 maxConnectNum: 100 #最大连接数 maxConnectPerRoute: 100 #最大路由连接数

读取配置文件

package com.woyaoce.paperapi.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Configuration;@Configuration@ConfigurationProperties(prefix = "es")public class ElasticsearchProperties { public String getHosts() { return hosts; } public void setHosts(String hosts) { this.hosts = hosts; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public int getConnectTimeOut() { return connectTimeOut; } public void setConnectTimeOut(int connectTimeOut) { this.connectTimeOut = connectTimeOut; } public int getSocketTimeOut() { return socketTimeOut; } public void setSocketTimeOut(int socketTimeOut) { this.socketTimeOut = socketTimeOut; } public int getConnectionRequestTimeOut() { return connectionRequestTimeOut; } public void setConnectionRequestTimeOut(int connectionRequestTimeOut) { this.connectionRequestTimeOut = connectionRequestTimeOut; } public int getMaxConnectNum() { return maxConnectNum; } public void setMaxConnectNum(int maxConnectNum) { this.maxConnectNum = maxConnectNum; } public int getMaxConnectPerRoute() { return maxConnectPerRoute; } public void setMaxConnectPerRoute(int maxConnectPerRoute) { this.maxConnectPerRoute = maxConnectPerRoute; } private String hosts; private int port; private String username; private String password; private String schema; private int connectTimeOut; private int socketTimeOut; private int connectionRequestTimeOut; private int maxConnectNum; private int maxConnectPerRoute;}

配置

package com.woyaoce.paperapi.config;import com.woyaoce.paperapi.properties.ElasticsearchProperties;import org.apache.http.HttpHost;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.CredentialsProvider;import org.apache.http.impl.client.BasicCredentialsProvider;import org.elasticsearch.client.RestClient;import org.elasticsearch.client.RestClientBuilder;import org.elasticsearch.client.RestHighLevelClient;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import javax.annotation.Resource;@Configuration@EnableConfigurationProperties({ElasticsearchProperties.class})public class RestHighLevelClientConfig { @Resource private ElasticsearchProperties elasticsearchProperties; @Bean(destroyMethod = "close") public RestHighLevelClient client() { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword())); RestClientBuilder builder = RestClient.builder(new HttpHost(elasticsearchProperties.getHosts(), elasticsearchProperties.getPort(), elasticsearchProperties.getSchema())); // 异步httpclient连接延时配置 builder.setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(elasticsearchProperties.getConnectTimeOut()); requestConfigBuilder.setSocketTimeout(elasticsearchProperties.getSocketTimeOut()); requestConfigBuilder.setConnectionRequestTimeout(elasticsearchProperties.getConnectionRequestTimeOut()); return requestConfigBuilder; }); // 异步httpclient连接数配置 builder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setMaxConnTotal(elasticsearchProperties.getMaxConnectNum()); httpClientBuilder.setMaxConnPerRoute(elasticsearchProperties.getMaxConnectPerRoute()); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); return httpClientBuilder; }); RestHighLevelClient client = new RestHighLevelClient(builder); return client; }}

测试

package com.app.appapi.core.es.service;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.app.appapi.aop.LoggerAop;import com.app.appapi.core.buyer.vo.BuyerIndexServiceVo;import com.app.appapi.core.es.vo.Infodocument;import com.app.appapi.core.es.vo.TestServiceIndexdocumentNew;import com.app.appapi.result.PageResult;import org.apache.lucene.search.Sort;import org.apache.lucene.search.SortField;import org.elasticsearch.action.search.SearchRequest;import org.elasticsearch.action.search.SearchResponse;import org.elasticsearch.client.RequestOptions;import org.elasticsearch.client.RestHighLevelClient;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.search.SearchHit;import org.elasticsearch.search.SearchHits;import org.elasticsearch.search.aggregations.Aggregation;import org.elasticsearch.search.aggregations.AggregationBuilders;import org.elasticsearch.search.aggregations.Aggregations;import org.elasticsearch.search.aggregations.bucket.terms.Terms;import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;import org.elasticsearch.search.aggregations.metrics.Cardinality;import org.elasticsearch.search.aggregations.metrics.MaxAggregationBuilder;import org.elasticsearch.search.aggregations.metrics.TopHits;import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder;import org.elasticsearch.search.aggregations.pipeline.BucketSortPipelineAggregationBuilder;import org.elasticsearch.search.builder.SearchSourceBuilder;import org.elasticsearch.search.sort.FieldSortBuilder;import org.elasticsearch.search.sort.SortBuilder;import org.elasticsearch.search.sort.SortBuilders;import org.elasticsearch.search.sort.SortOrder;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Service;import java.io.IOException;import java.lang.reflect.Array;import java.util.ArrayList;import java.util.List;import java.util.Map;@Servicepublic class TestServiceSearchService { @Autowired private RestHighLevelClient client; private String indexName = "woyaoce_index_service_new"; private static Logger log = LoggerFactory.getLogger(LoggerAop.class); public List getListByServiceIdList(List serviceIdList) { List documentNewList = new ArrayList<>(); SearchRequest searchRequest = new SearchRequest(indexName); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("id", serviceIdList)); searchRequest.source(builder); SearchResponse response; try { response = client.search(searchRequest, RequestOptions.DEFAULT); } catch (IOException e) { e.printStackTrace(); return documentNewList; } SearchHit[] searchHits = response.getHits().getHits(); for (SearchHit searchHit : searchHits) { Map sourceAsMap = searchHit.getSourceAsMap(); String jsonString = JSON.toJSONString(sourceAsMap); TestServiceIndexdocumentNew infodocument = JSONObject.parseObject(jsonString, TestServiceIndexdocumentNew.class); documentNewList.add(infodocument); } return documentNewList; } }

参考:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.16/java-rest-high.html

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。