즐겁게/elasticsearch-8

elasticsearch-7.x RestHighLevelClient Connect

파이브빈즈 2022. 9. 29. 23:39

elasticsearch-7.x용 java connect client: RestHighLevelClient를 이용

 

public class ElasticConnect {
	private static Logger log = LoggerFactory.getLogger(ElasticConnect.class);
	private static RestHighLevelClient client = null;

	public static synchronized RestHighLevelClient getClient() {
		if( !isValidConnection()){
			// 아이피1:9200;아이피2:9200
			String nodes = "설정파일에서 읽어들인 값";
			// elastic에 user/passwd 가 설정되어 있어야 함
			// user/passwd설정: bin/elasticsearch-users useradd 아이디 -p 비번 -r superuser
			String user = "설정파일에서 읽어들인 값";
			String passwd = "설정파일에서 읽어들인 값";

			new ElasticConnect().initConnect(nodes, user, passwd);
		}
		
		return client;
	}

	private void initConnect(String nodes, String user, String passwd) {
		try {
			RestClientBuilder builder = null;

			// nodes = 아이피1:9200;아이피2:9200...
			String[] clients = StringUtils.split(nodes, ";");
			HttpHost[] httpHosts = new HttpHost[clients.length];
	
			for(int i=0; i<clients.length; i++){
				String[] clienthost = StringUtils.split(clients[i], ":");
				if(clienthost.length > 1){
					String host = clienthost[0];
					int port = Integer.parseInt(clienthost[1]);
					httpHosts[i] = new HttpHost(host, port, "http");
				}
			}

			if(StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(passwd)) {
				CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
				credentialsProvider.setCredentials(AuthScope.ANY,
						new UsernamePasswordCredentials(user, passwd));

				builder = RestClient.builder(httpHosts)
						.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
							@Override
							public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
								return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
							}
						});
			} else {
				builder = RestClient.builder(httpHosts);
			}

			client = new RestHighLevelClient(builder);
		}catch(Exception e) {
			try { if(client != null) client.close(); client = null; } catch(Exception ee) {}
			log.error("innitConnect error: {}", e);
		}		
	}

	public static boolean isValidConnection() {
		boolean bResult = false;
		try {
			if(client == null) return false;
			bResult = client.ping(RequestOptions.DEFAULT);
		}catch(Exception e) {}
		
		return bResult;
	}

	public static void close(){
		try {
			if(client != null) {
				client.close();
				client = null;
			}
		}catch(Exception e) {}
	}

	/** Connect Test **/
	public static void main(String[] args) {
		try ( RestHighLevelClient client = ElasticConnect.getClient() ){
			if(ElasticConnect.isValidConnection()) {
				System.out.println("connected");
				Thread.sleep(10000);
				System.out.println("bye~~");
			} else {
				System.out.println("not connected");
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}