ElasticSearch 测试连接工具(TestConnection)

来源:互联网 发布:如何网络编辑 编辑:程序博客网 时间:2024/06/05 04:54

截止到0.90.x的版本,Elasticsearch已经将connectedNodes从api中去掉,具体代替的方法是什么呢?也没有找到相关的说明。

因此决定自己手工写一个工具类。其实,我们只有通过API去执行一个方法,就可以测试连接是否正常。测试的方法选定为获得集群node的信息。测试代码:

Java代码
  1. import java.util.Map;  

  2. import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;  

  3. import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;  

  4. import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;  

  5. import org.elasticsearch.client.Client;  

  6.  

  7. import com.donlianli.es.ESUtils;  

  8. /**

  9. * @author donlianli@126.com

  10. * 测试服务器的可用状态

  11. */  

  12. public class TestConnection {  

  13.    /**

  14.     * 测试ES可用连接数方法

  15.     * 同时也也可以用以校验ES是否可以连接上

  16.     */  

  17.    public static void main(String[] args) {  

  18.        //通过transport方式连接哦,否则没有意义了  

  19.        Client client = ESUtils.getClient();  

  20.        try{  

  21.            NodesInfoResponse response = client.admin().cluster()  

  22.                    //超时时间设置为半分钟  

  23.                    .nodesInfo(new NodesInfoRequest().timeout("30")).actionGet();  

  24.            Map<String,NodeInfo> nodesMap = response.getNodesMap();  

  25.            //打印节点信息  

  26.            for(Map.Entry<String, NodeInfo> entry : nodesMap.entrySet()){  

  27.                System.out.println(entry.getKey() + ":" + entry.getValue().getServiceAttributes()) ;  

  28.            }  

  29.        }  

  30.        catch(Exception e){  

  31.            e.printStackTrace();  

  32.            System.out.println("无法连接到Elasticsearch");  

  33.        }  

  34.    }  

  35. }  


0 0
原创粉丝点击