ElasticSearch 测试连接工具(TestConnection)

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

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

import java.util.Map;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoRequest;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.client.Client;

import com.donlianli.es.ESUtils;
/**
 * @author [email protected]
 * 测试服务器的可用状态
 */
public class TestConnection {
	/**
	 * 测试ES可用连接数方法
	 * 同时也也可以用以校验ES是否可以连接上
	 */
	public static void main(String[] args) {
		//通过transport方式连接哦,否则没有意义了
		Client client = ESUtils.getClient();
		try{
			NodesInfoResponse response = client.admin().cluster()
					//超时时间设置为半分钟
					.nodesInfo(new NodesInfoRequest().timeout("30")).actionGet();
	        Map<String,NodeInfo> nodesMap = response.getNodesMap();
	        //打印节点信息
	    	for(Map.Entry<String, NodeInfo> entry : nodesMap.entrySet()){
	    		System.out.println(entry.getKey() + ":" + entry.getValue().getServiceAttributes()) ;
	    	}
		}
		catch(Exception e){
			e.printStackTrace();
			System.out.println("无法连接到Elasticsearch");
		}
	}
}

猜你喜欢

转载自donlianli.iteye.com/blog/1922822