SpringBoot-data整合ElasticSearch集群,使用Reactor 和ES High level Rest Client

application.yml中添加配置:

spring:
     elasticsearch:
        rest:
          uris: http://172.66.20.2:9200,http://172.66.20.3:9200
          username: elasticsearch
          password: elasticsearch

java配置类:


import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
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.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.museframework.management.ManagementConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import javax.net.ssl.SSLContext;

@Configuration
@Import(ElasticsearchAutoConfiguration.class)
@EnableElasticsearchRepositories(basePackageClasses = OnlineTraceRespository.class)
@ConditionalOnProperty(value = ManagementConfiguration.MANANGEMENT_PREFIX + ".trace-query", havingValue = "true")
@ConditionalOnClass({ ElasticsearchTemplate.class, AbstractElasticsearchConfiguration.class })
public class TransTraceConfiguration extends AbstractElasticsearchConfiguration {
	@Value("#{'${spring.elasticsearch.rest.uris}'.split(',')}")
	String[] uris;
	@Value("${spring.elasticsearch.rest.username:}")
	String username;
	@Value("${spring.elasticsearch.rest.password:}")
	String password;

	@Value("${spring.elasticsearch.rest.socket-timeout}")
	int socketTimeout;

	@Override
	public RestHighLevelClient elasticsearchClient() {
		HttpHost[] hosts = new HttpHost[uris.length];

		for (int i = 0; i < uris.length; i++) {
			hosts[i] = (HttpHost.create(uris[i]));
		}

		RestClientBuilder clientBuilder = RestClient.builder(hosts);
		clientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
			@SneakyThrows
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
					CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
					UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
					credentialsProvider.setCredentials(AuthScope.ANY, credentials);
					httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				}
				IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(100)
						.setConnectTimeout(10000).setSoTimeout(10000).build();
				httpClientBuilder.setDefaultIOReactorConfig(ioReactorConfig);
				SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
					@Override
					public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
						return true;
					}
				}).build();
				httpClientBuilder.setSSLContext(sslContext);
				httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
				return httpClientBuilder;
			}
		});

		return new RestHighLevelClient(clientBuilder);
	}
}

Repository类:


import com.ibm.banking.musemvp.parameter.entity.BatchTraceEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BatchTraceRepository extends ElasticsearchRepository {
//空类,哈哈,简单就是美
}

调用代码:

    public List searchJobSliceInfo(Integer jobId, String startEnd) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termsQuery("mainJobId", jobId+"")); //ES里面这个字段是文本类型,要转一下
        if (StringUtils.isNotBlank(startEnd)) {
            boolQueryBuilder.must(QueryBuilders.termsQuery("jobAction", startEnd.toLowerCase()));
        }
        ArrayList slices = new ArrayList<>(40);
        batchTraceRepository.search(boolQueryBuilder).forEach(s -> slices.add(s));
        return slices;
    }

你可能感兴趣的:(spring,boot,elasticsearch,reactor)