#客户端基本配置 elasticsearch-client.hosts=http://localhost:9200 elasticsearch-client.username=elastic elasticsearch-client.password=123321
@ConfigurationProperties(prefix = "elasticsearch-client") public class ElasticsearchClientBean { private Listhosts; private String username; private String password; public List getHosts() { return hosts; } public void setHosts(List hosts) { this.hosts = hosts; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "ElasticsearchClientBean{" + "hosts=" + hosts + ", username='" + username + ''' + ", password='" + password + ''' + '}'; } }
@Configuration public class ElasticsearchClientConfig { @Autowired private ElasticsearchClientBean properties; private RestHighLevelClient client; private RestClient restClient; @Bean public RestHighLevelClient getRestHighLevelClient() { HttpHost[] hosts = properties.getHosts().stream().map(h -> HttpHost.create(h)).toArray(HttpHost[]::new); //TODO 基础身份验证 设置账户密码时打开 final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(properties.getUsername(), properties.getPassword())); client = new RestHighLevelClient( RestClient.builder(hosts) //TODO 身份验证 设置账户密码时打开 .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.disableAuthCaching() .setDefaultCredentialsProvider(credentialsProvider) .setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(8).build()) ) .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(300000) .setSocketTimeout(300000) .setConnectionRequestTimeout(300000) ) ); System.out.println("Connecting Elasticsearch..."); while (true) { try { if (client.ping(RequestOptions.DEFAULT)) { break; } } catch (Exception e) { System.out.println("Connecting Elasticsearch Failed, Retry in 10 seconds..."); try { Thread.sleep(10000); } catch (InterruptedException e1) { e.printStackTrace(); } } } System.out.println("Elasticsearch Connected!"); return client; } public void close() { if(client != null) { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } public RestClient getLowLevelClient() { if (restClient == null && client != null){ restClient = client.getLowLevelClient(); } return restClient; } public boolean connectionEs() { try { ListesHttp = properties.getHosts(); for (String http : esHttp) { String text = HttpClientUtil.get(properties.getUsername(),properties.getPassword(),http + "/_cluster/health"); if(text == null || StringUtils.isEmpty(text)){ System.out.println("Start:connectionEs: "+http+":Error"); continue; } return true; } } catch (Exception e) { e.printStackTrace(); } return false; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)