org.elasticsearch.client.RestClientBuilder类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(479)

本文整理了Java中org.elasticsearch.client.RestClientBuilder类的一些代码示例,展示了RestClientBuilder类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。RestClientBuilder类的具体详情如下:
包路径:org.elasticsearch.client.RestClientBuilder
类名称:RestClientBuilder

RestClientBuilder介绍

[英]Helps creating a new RestClient. Allows to set the most common http client configuration options when internally creating the underlying org.apache.http.nio.client.HttpAsyncClient. Also allows to provide an externally created org.apache.http.nio.client.HttpAsyncClient in case additional customization is needed.
[中]帮助创建新的RestClient。允许在内部创建基础组织时设置最常见的http客户端配置选项。阿帕奇。http。尼奥。客户HttpAsyncClient。还允许提供外部创建的组织。阿帕奇。http。尼奥。客户HttpAsyncClient,以防需要额外定制。

代码示例

代码示例来源:origin: apache/incubator-gobblin

RestClientBuilder builder = RestClient.builder(httpHosts);
 builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
 builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder
builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
  .setConnectionRequestTimeout(0)); // Important, otherwise the client has spurious timeouts
return builder.build();

代码示例来源:origin: apache/storm

/**
   * Creates a new {@link RestClient} using given {@link EsConfig}.
   *
   * @return {@link RestClient} for Elasticsearch connection
   */
  public RestClient construct() {
    RestClientBuilder builder = RestClient.builder(esConfig.getHttpHosts());
    if (esConfig.getMaxRetryTimeoutMillis() != null) {
      builder.setMaxRetryTimeoutMillis(esConfig.getMaxRetryTimeoutMillis());
    }
    if (esConfig.getDefaultHeaders() != null) {
      builder.setDefaultHeaders(esConfig.getDefaultHeaders());
    }
    if (esConfig.getFailureListener() != null) {
      builder.setFailureListener(esConfig.getFailureListener());
    }
    if (esConfig.getHttpClientConfigCallback() != null) {
      builder.setHttpClientConfigCallback(esConfig.getHttpClientConfigCallback());
    }
    if (esConfig.getRequestConfigCallback() != null) {
      builder.setRequestConfigCallback(esConfig.getRequestConfigCallback());
    }
    if (esConfig.getPathPrefix() != null) {
      builder.setPathPrefix(esConfig.getPathPrefix());
    }
    return builder.build();
  }
}

代码示例来源:origin: apache/flink

@Override
public void configureRestClientBuilder(RestClientBuilder restClientBuilder) {
  if (maxRetryTimeout != null) {
    restClientBuilder.setMaxRetryTimeoutMillis(maxRetryTimeout);
  }
  if (pathPrefix != null) {
    restClientBuilder.setPathPrefix(pathPrefix);
  }
}

代码示例来源:origin: testcontainers/testcontainers-java

private RestClient getClient(ElasticsearchContainer container) {
  if (client == null) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
      new UsernamePasswordCredentials(ELASTICSEARCH_USERNAME, ELASTICSEARCH_PASSWORD));
    client = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
      .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
      .build();
  }
  return client;
}

代码示例来源:origin: jooby-project/jooby

@Override
public void configure(final Env env, final Config config, final Binder binder) {
 HttpHost[] httpHosts = Arrays.stream(hosts).map(HttpHost::create).toArray(HttpHost[]::new);
 RestClient restClient = RestClient.builder(httpHosts).build();
 binder.bind(RestClient.class).toInstance(restClient);
 env.onStop(restClient::close);
}

代码示例来源:origin: tmobile/pacbot

private RestClient getRestClient() {
  if (restClient == null) {
    RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, esPort));
    builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
      @Override
      public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
        return requestConfigBuilder.setConnectionRequestTimeout(0);
      }
    });
    restClient = builder.build();
  }
  return restClient;
}

代码示例来源:origin: dadoonet/fscrawler

private static RestClientBuilder buildRestClient(Elasticsearch settings) {
  List<HttpHost> hosts = new ArrayList<>(settings.getNodes().size());
  settings.getNodes().forEach(node -> hosts.add(HttpHost.create(node.getDecodedUrl())));
  RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()]));
  if (settings.getUsername() != null) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
    builder.setHttpClientConfigCallback(httpClientBuilder ->
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
  }
  return builder;
}

代码示例来源:origin: HuygensING/timbuctoo

@JsonCreator
public ElasticSearchFilter(@JsonProperty("hostname") String hostname, @JsonProperty("port") int port,
              @JsonProperty("username") Optional<String> username,
              @JsonProperty("password") Optional<String> password) {
 Header[] headers = {
  new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
  new BasicHeader("Role", "Read")};
 final RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostname, port))
  .setDefaultHeaders(headers);
 if (username.isPresent() && !username.get().isEmpty() && password.isPresent() && !password.get().isEmpty()) {
  final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(
   AuthScope.ANY,
   new UsernamePasswordCredentials(username.get(), password.get())
  );
  restClientBuilder.setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credentialsProvider));
 }
 restClient = restClientBuilder.build();
 mapper = new ObjectMapper();
}

代码示例来源:origin: com.eurodyn.qlack2.util/qlack2-util-avail-check-elasticsearch

new UsernamePasswordCredentials(user, password));
 restClient = RestClient
  .builder(new HttpHost(url.split(":")[0], Integer.parseInt(url.split(":")[1])))
  .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
   @Override
   public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
  }).build();
} else {
 restClient = RestClient
  .builder(new HttpHost(url.split(":")[0], Integer.parseInt(url.split(":")[1]))).build();
while (Instant.now().toEpochMilli() - startTime < maxWait && !retVal) {
 try {
  final Response response = restClient.performRequest("GET", "_cluster/health");
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode == 200) {

代码示例来源:origin: org.elasticsearch.plugin/reindex-client

RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme()))
  .setDefaultHeaders(clientHeaders)
  .setRequestConfigCallback(c -> {
    c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
    c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
    return c;
  })
  .setHttpClientConfigCallback(c -> {
  });
if (Strings.hasLength(remoteInfo.getPathPrefix()) && "/".equals(remoteInfo.getPathPrefix()) == false) {
  builder.setPathPrefix(remoteInfo.getPathPrefix());
return builder.build();

代码示例来源:origin: couchbase/couchbase-elasticsearch-connector

public static RestHighLevelClient newElasticsearchClient(List<HttpHost> hosts, String username, String password, boolean secureConnection, Supplier<KeyStore> trustStore) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
 final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
 credentialsProvider.setCredentials(AuthScope.ANY,
   new UsernamePasswordCredentials(username, password));
 final SSLContext sslContext = !secureConnection ? null :
   SSLContexts.custom().loadTrustMaterial(trustStore.get(), null).build();
 final RestClientBuilder builder = RestClient.builder(Iterables.toArray(hosts, HttpHost.class))
   .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
     .setSSLContext(sslContext)
     .setDefaultCredentialsProvider(credentialsProvider))
   .setFailureListener(new RestClient.FailureListener() {
    @Override
    public void onFailure(HttpHost host) {
     Metrics.elasticsearchHostOffline().mark();
    }
   });
 return new RestHighLevelClient(builder);
}

代码示例来源:origin: gauravrmazra/gauravbytes

public static RestClient createClientWithDefaultHeaders() {
  RestClientBuilder clientBuilder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
  
  Header[] defaultHeaders = new Header[2];
  defaultHeaders[0] = new BasicHeader("COMPANY", "GAURAVBYTES");
  defaultHeaders[1] = new BasicHeader("OWNER", "Gaurav Rai Mazra");
  
  clientBuilder.setDefaultHeaders(defaultHeaders);
  clientBuilder.setFailureListener(failureListener());
  return clientBuilder.build();
}

代码示例来源:origin: apache/incubator-griffin

public MetricStoreImpl(@Value("${elasticsearch.host}") String host,
            @Value("${elasticsearch.port}") int port,
            @Value("${elasticsearch.scheme:http}") String scheme,
            @Value("${elasticsearch.user:}") String user,
            @Value("${elasticsearch.password:}") String password) {
  HttpHost httpHost = new HttpHost(host, port, scheme);
  RestClientBuilder builder = RestClient.builder(httpHost);
  if (!user.isEmpty() && !password.isEmpty()) {
    String encodedAuth = buildBasicAuthString(user, password);
    Header[] requestHeaders = new Header[]{
        new BasicHeader(org.apache.http.HttpHeaders.AUTHORIZATION,
            encodedAuth)};
    builder.setDefaultHeaders(requestHeaders);
  }
  this.client = builder.build();
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.APPLICATION_JSON);
  this.responseHeaders = responseHeaders;
  String urlBase = String.format("/%s/%s", INDEX, TYPE);
  this.urlGet = urlBase.concat("/_search?filter_path=hits.hits._source");
  this.urlPost = urlBase.concat("/_bulk");
  this.urlDelete = urlBase.concat("/_delete_by_query");
  this.indexMetaData = String.format(
      "{ \"index\" : { \"_index\" : " +
          "\"%s\",\"_type\" : \"%s\" } }%n",
      INDEX,
      TYPE);
  this.mapper = new ObjectMapper();
}

代码示例来源:origin: spring-projects/spring-data-elasticsearch

RestClientBuilder builder = RestClient.builder(httpHosts);
HttpHeaders headers = clientConfiguration.getDefaultHeaders();
  builder.setDefaultHeaders(httpHeaders);
builder.setHttpClientConfigCallback(clientBuilder -> {

代码示例来源:origin: org.nuxeo.elasticsearch/nuxeo-elasticsearch-core

protected ESClient createRestClient(ElasticSearchClientConfig config) {
  String addressList = config.getOption("addressList", "");
  if (addressList.isEmpty()) {
    throw new IllegalArgumentException("No addressList option provided cannot connect RestClient");
  }
  String[] hosts = addressList.split(",");
  HttpHost[] httpHosts = new HttpHost[hosts.length];
  int i = 0;
  for (String host : hosts) {
    httpHosts[i++] = HttpHost.create(host);
  }
  RestClientBuilder builder = RestClient.builder(httpHosts)
                     .setRequestConfigCallback(
                         requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(
                             getConnectTimeoutMs(config))
                                               .setSocketTimeout(
                                                   getSocketTimeoutMs(
                                                       config)))
                     .setMaxRetryTimeoutMillis(getConnectTimeoutMs(config));
  addClientCallback(config, builder);
  RestHighLevelClient client = new RestHighLevelClient(builder); // NOSONAR (factory)
  // checkConnection(client);
  return new ESRestClient(client.getLowLevelClient(), client);
}

代码示例来源:origin: org.elasticsearch.client/elasticsearch-rest-high-level-client

/**
 * Creates a {@link RestHighLevelClient} given the low level {@link RestClientBuilder} that allows to build the
 * {@link RestClient} to be used to perform requests and parsers for custom response sections added to Elasticsearch through plugins.
 */
protected RestHighLevelClient(RestClientBuilder restClientBuilder, List<NamedXContentRegistry.Entry> namedXContentEntries) {
  this(restClientBuilder.build(), RestClient::close, namedXContentEntries);
}

代码示例来源:origin: org.nuxeo.elasticsearch/nuxeo-elasticsearch-core

private void addClientCallback(ElasticSearchClientConfig config, RestClientBuilder builder) {
  BasicCredentialsProvider credentialProvider = getCredentialProvider(config);
  SSLContext sslContext = getSslContext(config);
  if (sslContext == null && credentialProvider == null) {
    return;
  }
  builder.setHttpClientConfigCallback(httpClientBuilder -> {
    httpClientBuilder.setSSLContext(sslContext);
    httpClientBuilder.setDefaultCredentialsProvider(credentialProvider);
    return httpClientBuilder;
  });
}

代码示例来源:origin: Netflix/conductor

@Override
public RestClient get() {
  return RestClient.builder(convertToHttpHosts(configuration.getURIs())).build();
}

代码示例来源:origin: datacleaner/DataCleaner

private ElasticSearchRestClient getClientForRestProtocol() {
  final String scheme = _ssl ? "https" : "http";
  final HttpHost hosts = new HttpHost(_hostname, _port, scheme);
  final RestClientBuilder restClientBuilder = RestClient.builder(hosts);
  if (!Strings.isNullOrEmpty(_username)) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(_username, _password));
    restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
      @Override
      public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      }
    });
  }
  final ElasticSearchRestClient elasticSearchRestClient = new ElasticSearchRestClient(restClientBuilder.build());
  return elasticSearchRestClient;
}

代码示例来源:origin: tmobile/pacbot

private RestClient getRestClient() {
    if (restClient == null) {
      String esHost = config.getElasticSearch().getDevIngestHost();
      int esPort = config.getElasticSearch().getDevIngestPort();
      RestClientBuilder builder = RestClient.builder(new HttpHost(esHost, esPort));
      RequestConfigCallback requestConfigCallback = requestConfigBuilder -> requestConfigBuilder
          .setConnectionRequestTimeout(0);
      builder.setRequestConfigCallback(requestConfigCallback);
      restClient = builder.build();
    }
    return restClient;
  }
}

相关文章