shopping-mall/src/main/java/com/zcloud/config/ElasticsearchConfiguration....

94 lines
3.0 KiB
Java
Raw Normal View History

2025-05-16 16:54:08 +08:00
package com.zcloud.config;
import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
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.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
@Data
public class ElasticsearchConfiguration {
private String host;
private int port;
private String username;
private String password;
/**
* HttpHost
*
* @return
*/
private HttpHost toHttpHost() {
HttpHost httpHost = new HttpHost(host, port, "http");
return httpHost;
}
/**
*
*
* @return
* @throws Exception
*/
@Bean
public ElasticsearchClient clientBySync() throws Exception {
ElasticsearchTransport transport = getElasticsearchTransport(username, password, toHttpHost());
return new ElasticsearchClient(transport);
}
/**
*
*
* @return
* @throws Exception
*/
@Bean
public ElasticsearchAsyncClient clientByAsync() throws Exception {
ElasticsearchTransport transport = getElasticsearchTransport(username, password, toHttpHost());
return new ElasticsearchAsyncClient(transport);
}
/**
*
*
* @return
* @throws Exception
*/
@Bean
public ElasticsearchTransport getTransport() throws Exception {
return getElasticsearchTransport(username, password, toHttpHost());
}
private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost... hosts) {
// 账号密码的配置
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));
RestClientBuilder.HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
.setDefaultCredentialsProvider(credentialsProvider);
// 用builder创建RestClient对象
RestClient client = RestClient
.builder(hosts)
.setHttpClientConfigCallback(callback)
.build();
return new RestClientTransport(client, new JacksonJsonpMapper());
}
}