首先,我们尝试嵌入节点的方式,有如下三种方式(区别如下注释):
@Test public void testDefaultNode(){ //默认配置(数据节点)启动一个节点,会自动加入同网段的es集群,前提就是es的集群名(cluster.name)参数要设置一致 //默认状态下es集群会自动给它分配一些索引的分片 //会加入集群 Node node = NodeBuilder.nodeBuilder().build(); Client client = node.client(); ClusterAdminClient cluster = client.admin().cluster(); System.out.println(cluster.toString()); node.close(); }
@Test public void testClientNode(){ //客户端配置(客户端节点,不保存任何数据) //作为一个客户端而不去保存数据,就可以设置把node.data设置成false或 node.client设置成true //会加入集群 Node node = NodeBuilder.nodeBuilder().client(true).node(); Client client = node.client(); ClusterAdminClient cluster = client.admin().cluster(); System.out.println(cluster.toString()); node.close(); }
@Test public void testLocalNode(){ //本地节点 //不会加入集群 //本地单元测试 Node node = NodeBuilder.nodeBuilder().local(true).node(); Client client = node.client(); ClusterAdminClient cluster = client.admin().cluster(); System.out.println(cluster.toString()); node.close(); }
第二种方式(TransportClient接口):
@Test public void testTransportClient(){ //可以不启动节点就与es集群通信,只需要指定es集群中其中一台或多台机的ip地址和端口 Client client = new TransportClient() .addTransportAddress(new InetSocketTransportAddress("192.168.1.135", 9300)) .addTransportAddress(new InetSocketTransportAddress("192.168.1.131", 9300)) .addTransportAddress(new InetSocketTransportAddress("192.168.1.132", 9300)) .addTransportAddress(new InetSocketTransportAddress("192.168.1.133", 9300)); client.close(); }
借此说明一下两个配置参数:
@Test public void updateClusterName(){ //更改集群名 Settings settings = ImmutableSettings.settingsBuilder() .put("cluster.name", "myClusterName").build(); Client client = new TransportClient(settings); client.close(); }
@Test public void autoDiscoveryNode(){ //设置client.transport.sniff为true来使客户端去嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中 Settings settings = ImmutableSettings.settingsBuilder() .put("client.transport.sniff", true).build(); Client client = new TransportClient(settings); client.close(); }
程序猿行业技术生活交流群:181287753(指尖天下),欢迎大伙加入交流学习。