es5.3【2】获取client

相关环境:jdk1.8、es5.3、eclipse&maven
jar包版本


            org.elasticsearch.client
            transport
            5.1.1


            com.alibaba
            fastjson
            1.2.47

获取ES client

package com.yb.es;

import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

public class ESUtils {
	public static void main(String[] args) {
		getClient();
	}

	public static Client client = null;

	public static Client getClient() {
		if (client != null) {
			return client;
		}
		client = getSpecifiedClient("[email protected]");
		return client;
	}

	private static Client getSpecifiedClient(String clientNameStr) {
		if (clientNameStr == null) {
			return null;
		}
		String[] ss = clientNameStr.split("@");
		int port = 9300;
		try {
			Settings settings = Settings.builder().put("cluster.name", ss[0]).put("client.transport.sniff", true)
					.build();
			client = new PreBuiltTransportClient(settings)
					.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ss[1]), port));

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		return client;
	}

}

相关异常
NodeDisconnectedException:客户端和服务端es版本不一致,修改jar包版本匹配服务端es即可

你可能感兴趣的:(es5.3【2】获取client)