ElasticSearch学习(十三)在Java应用中实现集群管理

package Test;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.health.ClusterIndexHealth;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import java.net.InetAddress;

public class CluterDemo {

    @Test
    public void test1() throws Exception {

        //指定ES集群
        Settings settings = Settings.builder().put("cluster.name", "my-application").build();

        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.123.101"),9300));


        ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth().get();
        //得到集群的名称
        String clusterName = healthResponse.getClusterName();
        System.out.println("clusterName = "+clusterName);

        //得到用于存放数据的节点
        int numberOfDataNodes = healthResponse.getNumberOfDataNodes();
        System.out.println("numberOfDataNodes = "+numberOfDataNodes);

        //得到所有的节点
        int numberOfNodes = healthResponse.getNumberOfNodes();
        System.out.println("numberOfNodes = "+numberOfNodes);

        for (ClusterIndexHealth health : healthResponse.getIndices().values()){
            //当前索引的名称
            String index = health.getIndex();
            //索引由多少个主分片
            int numberOfShards = health.getNumberOfShards();
            //有多少个副本
            int numberOfReplicas = health.getNumberOfReplicas();
            System.out.printf("index = %s,numberOfShards = %d,numberOfReplicas =%d\n",index,numberOfShards,numberOfReplicas);

            //得到当前的健康状况
            ClusterHealthStatus status = health.getStatus();
            System.out.println(status.toString());
        }


    }

}

 

你可能感兴趣的:(ElasticSearch)