EsClientUtil.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.yihu.quota.etl.util;
  2. import com.yihu.quota.etl.extract.es.EsExtract;
  3. import io.searchbox.client.JestClient;
  4. import io.searchbox.client.JestClientFactory;
  5. import io.searchbox.client.config.HttpClientConfig;
  6. import org.elasticsearch.client.Client;
  7. import org.elasticsearch.client.transport.TransportClient;
  8. import org.elasticsearch.common.settings.Settings;
  9. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.beans.factory.annotation.Value;
  14. import org.springframework.stereotype.Component;
  15. import org.springframework.util.StringUtils;
  16. import java.net.InetAddress;
  17. import java.net.UnknownHostException;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.concurrent.ConcurrentHashMap;
  23. /**
  24. * Created by janseny on 2017/8/1
  25. */
  26. @Component
  27. public class EsClientUtil {
  28. private Logger logger = LoggerFactory.getLogger(EsExtract.class);
  29. /**
  30. * @param host "localhost"
  31. * @param port 9200
  32. * @return
  33. */
  34. public JestClient getJestClient(String host, Integer port) {
  35. String hostAddress="http://"+host+":"+port;
  36. JestClientFactory factory = new JestClientFactory();
  37. factory.setHttpClientConfig(new HttpClientConfig
  38. .Builder(hostAddress)
  39. .multiThreaded(true)
  40. //.discoveryEnabled(true)
  41. .readTimeout(60000)//30秒 -60s
  42. .build());
  43. return factory.getObject();
  44. }
  45. public Client getClient(String host, Integer port,String clusterName) {
  46. try {
  47. Settings settings = Settings.settingsBuilder()
  48. .put("cluster.name", StringUtils.isEmpty(clusterName)?"elasticsearch":clusterName)
  49. .put("client.transport.sniff", false)
  50. .build();
  51. Client client = TransportClient.builder().settings(settings).build()
  52. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
  53. return client;
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. return null;
  58. }
  59. }