栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

springboot 配置Elasticsearch

springboot 配置Elasticsearch

版本说明 :
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;


@Service
public 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/745988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号