通过TransportClient接入Elasticsearch集群
在使用Elasticsearch进行数据查询和管理时,许多用户依赖于TransportClient这一早期Java客户端,它通过封装原生API简化了与Elasticsearch集群的交互过程。CSS服务的Elasticsearch集群支持通过TransportClient进行数据查询和管理,用户只需要构造对应的结构即可对Elasticsearch集群进行访问。
TransportClient已经在Elasticsearch 7.0版本中被标记为弃用状态。为了获得更好的兼容性和功能支持,建议优先使用Java High Level REST Client。
前提条件
- Elasticsearch集群处于可用状态,而且是非安全模式的集群(TransportClient只支持用于访问非安全模式的集群)。
- 运行Java代码的服务器与Elasticsearch集群之间网络互通。
- 获取集群的内网访问地址,操作指导请参见网络配置。由于TransportClient仅适用于访问非安全模式的集群,因此只能通过内网地址访问集群。
- 确认服务器已安装Java,要求JDK版本为1.8及以上,JDK1.8官网下载地址:Java Downloads。
- 确认TransportClient版本:为确保更好的兼容性,建议使用与Elasticsearch集群同版本的TransportClient连接Elasticsearch集群。
引入依赖
在运行Java代码的服务器中引入Java依赖。通过Maven方式引入apache版本。
使用时需要将7.10.2替换为实际Java客户端的版本号。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>7.10.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.2</version>
</dependency>
接入集群
使用Elasticsearch TransportClient连接非安全模式的Elasticsearch集群,并查询索引“test”是否存在。代码示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest; import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.ExecutionException; public class Main { public static void main(String[] args) throws ExecutionException, InterruptedException, UnknownHostException { String cluster_name = "xxx"; String host1 = "xx.xx.xx.xx"; String host2 = "yy.yy.yy.yy"; Settings settings = Settings.builder() .put("client.transport.sniff",false) .put("cluster.name", cluster_name) .build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName(host1), 9300)) .addTransportAddress(new TransportAddress(InetAddress.getByName(host2), 9300)); IndicesExistsRequest indicesExistsRequest = new IndicesExistsRequest("test"); ActionFuture<IndicesExistsResponse> exists = client.admin().indices().exists(indicesExistsRequest); System.out.println(exists.get().isExists()); } } |
其中,cluster_name为集群的名称;host1、host2为集群节点的内网IP地址,可通过GET _cat/nodes命令查看节点的IP地址。
该示例代码为判断集群是否存在test索引,当返回“true”(索引存在)或“false”(索引不存在)时,表示正常返回查询结果,集群连接成功。