1 RestHighLevelClient介绍
默认情况下,ElasticSearch使用两个端口来监听外部TCP流量。
- 9200端口:用于所有通过HTTP协议进行的API调用。包括搜索、聚合、监控、以及其他任何使用HTTP协议的请求。所有的客户端库都会使用该端口与ElasticSearch进行交互。
- 9300端口:是一个自定义的二进制协议,用于集群中各节点之间的通信。用于诸如集群变更、主节点选举、节点加入/离开、分片分配等事项。
RestHighLevelClient是ES的Java客户端,它是通过HTTP与ES集群进行通信。
2 引入ES依赖
java
<!--引入es-high-level-client相关依赖 start-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.10.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
<!--引入es-high-level-client相关依赖 end-->
3 使用
3.1 es的配置
java
# es配置
# es用户名
elasticsearch.userName=elastic
# es密码
elasticsearch.password=elastic
# es host ip 地址(集群),多个以","间隔
elasticsearch.hosts=127.0.0.1:9200
# es 请求方式
elasticsearch.scheme=http
# es 连接超时时间(ms)
elasticsearch.connectTimeOut=1000
# es socket 连接超时时间(ms)
elasticsearch.socketTimeOut=30000
# es 请求超时时间(ms)
elasticsearch.connectionRequestTimeOut=500
# es 最大连接数
elasticsearch.maxConnectNum=100
# es 每个路由的最大连接数
elasticsearch.maxConnectNumPerRoute=100
3.2 es客户端配置类
java
/**
* restHighLevelClient 客户端配置类
*
*/
@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchConfig {
/**
* es host ip 地址(集群)
*/
private String hosts;
/**
* es用户名
*/
private String userName;
/**
* es密码
*/
private String password;
/**
* es 请求方式
*/
private String scheme;
/**
* es 连接超时时间
*/
private int connectTimeOut;
/**
* es socket 连接超时时间
*/
private int socketTimeOut;
/**
* es 请求超时时间
*/
private int connectionRequestTimeOut;
/**
* es 最大连接数
*/
private int maxConnectNum;
/**
* es 每个路由的最大连接数
*/
private int maxConnectNumPerRoute;
/**
* 如果@Bean没有指定bean的名称,那么方法名就是bean的名称
*/
@Bean(name = "restHighLevelClient")
public RestHighLevelClient restHighLevelClient() {
// 构建连接对象
RestClientBuilder builder = RestClient.builder(getEsHost());
// 连接延时配置
builder.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
});
// 连接数配置
builder.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectNumPerRoute);
httpClientBuilder.setDefaultCredentialsProvider(getCredentialsProvider());
return httpClientBuilder;
});
return new RestHighLevelClient(builder);
}
private HttpHost[] getEsHost() {
// 拆分地址(es为多节点时,不同host以逗号间隔)
List<HttpHost> hostLists = new ArrayList<>();
String[] hostList = hosts.split(",");
for (String addr : hostList) {
String host = addr.split(":")[0];
String port = addr.split(":")[1];
hostLists.add(new HttpHost(host, Integer.parseInt(port), scheme));
}
// 转换成 HttpHost 数组
return hostLists.toArray(new HttpHost[]{});
}
private CredentialsProvider getCredentialsProvider() {
// 设置用户名、密码
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
return credentialsProvider;
}
}
3.3 es的简单使用
3.3.1 操作es索引
java
/**
* 操作ES索引
*/
@Slf4j
@Service
public class EsIndexOperation {
@Resource
private RestHighLevelClient restHighLevelClient;
private final RequestOptions options = RequestOptions.DEFAULT;
/**
* 判断索引是否存在
*/
public boolean checkIndex(String index) {
try {
return restHighLevelClient.indices().exists(new GetIndexRequest(index), options);
} catch (Exception e) {
log.error("EsIndexOperation checkIndex error.", e);
}
return Boolean.FALSE;
}
/**
* 创建索引-待优化
*/
public boolean createIndex(String indexName, Map<String, Object> columnMap) {
try {
if (!checkIndex(indexName)) {
CreateIndexRequest request = new CreateIndexRequest(indexName);
if (columnMap != null && columnMap.size() > 0) {
Map<String, Object> source = new HashMap<>();
source.put("properties", columnMap);
request.mapping(source);
}
this.restHighLevelClient.indices().create(request, options);
return Boolean.TRUE;
}
} catch (Exception e) {
log.error("EsIndexOperation createIndex error.", e);
}
return Boolean.FALSE;
}
/**
* 删除索引
*/
public boolean deleteIndex(String indexName) {
try {
if (checkIndex(indexName)) {
DeleteIndexRequest request = new DeleteIndexRequest(indexName);
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, options);
return response.isAcknowledged();
}
} catch (Exception e) {
log.error("EsIndexOperation deleteIndex error.", e);
}
return Boolean.FALSE;
}
}
4 参考文献
(1)elasticsearch学习(七):es客户端RestHighLevelClient_炎升的博客