集成ElasticClient客户端
创建 Config 包
在包当中新建一个:ElasticSearchConfig.java,内容如下,主要的大致内容就是配置 ES 服务器的连接超时时长与请求相关的时长配置还有就是配置了 ES 服务器的地址:
/**
* @author BNTang
* @version V1.0
* @project SpringBoot-ElasticSearch-Pro
* @date Created in 2022/3/5 /005 17:49
* @description elasticsearch 配置类
**/
@Configuration
public class ElasticSearchConfig {
private final Log logger = LogFactory.getLog(ElasticSearchConfig.class);
@Value("${elasticsearch.hosts}")
private String elasticSearchHost;
@Value("${elasticsearch.connection.timeout}")
private int elasticSearchConnectionTimeOut;
@Value("${elasticsearch.connection.socket.timeout}")
private int elasticSearchCollectionSocketTimeOut;
@Value("${elasticsearch.connection.request.timeout}")
private int elasticSearchConnectionRequestTimeOut;
@Bean
public ElasticsearchClient elasticSearchClient() {
RestClient restClient = RestClient.builder(this.getElasticSearchHttpHosts())
.setRequestConfigCallback(builder -> {
builder.setConnectTimeout(elasticSearchConnectionTimeOut);
builder.setSocketTimeout(elasticSearchCollectionSocketTimeOut);
builder.setConnectionRequestTimeout(elasticSearchConnectionRequestTimeOut);
return builder;
})
.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(Node node) {
logger.error(node);
}
})
.build();
RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
private HttpHost[] getElasticSearchHttpHosts() {
String[] hosts = elasticSearchHost.split(",");
HttpHost[] httpHosts = new HttpHost[hosts.length];
for (int i = 0; i < hosts.length; i++) {
String host = hosts[i];
host = host.replaceAll("http://", "").replaceAll("https://", "");
httpHosts[i] = new HttpHost(host.split(":")[0], Integer.parseInt(host.split(":")[1]));
}
return httpHosts;
}
}
修改 application.yaml 文件,添加 ES 服务器地址与超时的相关配置:
# elasticsearch
elasticsearch:
# 如果有多个以逗号分割即可例如:xxxx,xxxx
hosts: 180.76.177.246:9200
connection:
timeout: 10000
request:
# 请求超时时长
timeout: 10000
socket:
timeout: 10000
到这里博主认为大差不差了,就先记录这么多吧,接下来就是利用该客户端进行操作ES即可。