ES 版本:7.12.1
附带解决[es/indices.exists] Missing [X-Elastic-Product] header
@Configuration
public class ESConfig {
@Value("${es.url}")
String esUrl;
@Value("${es.port}")
int esPort;
private RestClient restClient;
private ElasticsearchClient client;
private ElasticsearchTransport transport;
@Bean(name = "elasticsearchClient")
public ElasticsearchClient getElasticsearchClient() {
restClient = RestClient.builder(
new HttpHost(esUrl, esPort)
).setRequestConfigCallback(
requestConfigBuilder -> requestConfigBuilder
.setConnectTimeout(90000000)//25hours
.setSocketTimeout(90000000)
).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
//显式设置keepAliveStrategy
.setKeepAliveStrategy((httpResponse, httpContext) -> TimeUnit.MINUTES.toMillis(3))
//显式开启tcp keepalive
.setDefaultIOReactorConfig(IOReactorConfig.custom().setSoKeepAlive(true).build())
.setDefaultHeaders(
Collections.singletonList(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()))
)
//解决[es/indices.exists] Missing [X-Elastic-Product] header.
.addInterceptorLast((HttpResponseInterceptor) (response, context)
-> response.addHeader("X-Elastic-Product", "Elasticsearch"))).build();
// 使用Jackson映射器创建传输层
transport = new RestClientTransport(
restClient, new JacksonJsonpMapper()
);
// 创建API客户端
client = new ElasticsearchClient(transport);
return client;
}
public void close() {
if (client != null) {
try {
transport.close();
restClient.close();
} catch (IOException e) {
log.error("关闭es连接异常");
}
}
}
}