Elasticsearch。这是一种跨平台、轻量级的客户端,使用 RESTful 接口进行通信,支持 Elasticsearch 的所有功能,并且完全兼容所有 Elasticsearch 版本。
Java 高级客户端是 Elasticsearch 提供的官方客户端,它是 Elasticsearch 实现的一个完全支持 RESTful 的 HTTP 客户端,并提供了面向对象的 API,缩短了与 Elasticsearch 交互的距离。它使用简单方便,易于集成,Java 开发人员无需了解其底层实现细节,就可以使用 Elasticsearch 的各种功能。
Elasticsearch 仍然支持旧的 Transport Client API 和 Java API,但这些 API 已经过时并且不推荐使用,整合springBoot很容易出现版本冲突问题。不建议使用。
环境:
elasticsearch 7.6.0
springBoot 2.4.7
一、maven依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.5.4</version>
</dependency>
二、EsRestConfig
package com.esd.config;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.NodeSelector;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
@Configuration
public class EsRestConfig {
@Bean
public RestClient getClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是ip,参数2是HTTP端口,参数3是通信协议
RestClientBuilder clientBuilder = RestClient.builder(
new HttpHost("192.168.1.163", 9200, "http"),
new HttpHost("192.168.1.129", 9200, "http"),
new HttpHost("192.168.1.162", 9200, "http")
);
// 1.设置请求头
Header[] defaultHeaders = {new BasicHeader("header", "value")};
clientBuilder.setDefaultHeaders(defaultHeaders);
//
//2. 设置超时时间,多次尝试同一请求时应该遵守的超时。默认值为30秒,与默认套接字超时相同。若自定义套接字超时,则应相应地调整最大重试超时
clientBuilder.setMaxRetryTimeoutMillis(60000);
/**
*3.设置失败监听器,
*每次节点失败都可以监听到,可以作额外处理
*/
clientBuilder.setFailureListener(new RestClient.FailureListener() {
@Override
public void onFailure(Node node) {
super.onFailure(node);
System.out.println(node.getName() + "==节点失败了");
}
});
/** 4.配置节点选择器,客户端以循环方式将每个请求发送到每一个配置的节点上,
*发送请求的节点,用于过滤客户端,将请求发送到这些客户端节点,默认向每个配置节点发送,
*这个配置通常是用户在启用嗅探时向专用主节点发送请求(即只有专用的主节点应该被HTTP请求命中)
*/
clientBuilder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);
/*
*5. 配置异步请求的线程数量,Apache Http Async Client默认启动一个调度程序线程,以及由连接管理器使用的许多工作线程
*(与本地检测到的处理器数量一样多,取决于Runtime.getRuntime().availableProcessors()返回的数量)。线程数可以修改如下,
*这里是修改为1个线程,即默认情况
*/
clientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultIOReactorConfig(
IOReactorConfig.custom().setIoThreadCount(1).build()
);
}
});
/**
*6. 配置连接超时和套接字超时
*配置请求超时,将连接超时(默认为1秒)和套接字超时(默认为30秒)增加,
*这里配置完应该相应地调整最大重试超时(默认为30秒),即上面的setMaxRetryTimeoutMillis,一般于最大的那个值一致即60000
*/
clientBuilder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
@Override
public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
// 连接5秒超时,套接字连接60s超时
return requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000);
}
});
// 最后配置好的clientBuilder再build一下即可得到真正的Client
return clientBuilder.build();
}
}
三、测试Demo
import java.io.IOException;
import java.util.Date;
import cn.hutool.json.JSONObject;
import com.ikscrm.utils.SnowFlakeIdGenerator;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class SuperWebappApiApplicationTests {
@Autowired
private RestClient client;
@Test
void run() throws IOException {
Request request = new Request("GET", "/_cat/nodes");
Response response = null;
try {
response = client.performRequest(request);
} catch (IOException e) {
e.printStackTrace();
}
try {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
void insert() throws IOException {
EwDO ewO=new EwDO();
ewO.setId(SnowFlakeIdGenerator.nextId());
ewO.setRemark("小五");
ewO.setCreateTime(new Date());
ewO.setUpdateTime(new Date());
System.out.println(ewContactWayDO);
// 构造HTTP请求,第一个参数是请求方法,第二个参数是服务器的端点,host默认是http://localhost:9200,
// endpoint直接指定为index/type的形式
Request request = new Request("POST", new StringBuilder("/testindex/book/").append(ewO.getId()).toString());
JSONObject jsonObject = new JSONObject(ewO);
// 设置请求体并指定ContentType,如果不指定默认为APPLICATION_JSON
request.setJsonEntity(jsonObject.toString());
// 发送HTTP请求
Response response = client.performRequest(request);
// 获取响应体, id: AWXvzZYWXWr3RnGSLyhH
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
}
参考:https://blog.csdn.net/weixin_35720385/article/details/88870851