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

x33g5p2x  于2022-01-29 转载在 其他  
字(19.4k)|赞(0)|评价(0)|浏览(257)

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

TransportClient介绍

[英]The transport client allows to create a client that is not part of the cluster, but simply connects to one or more nodes directly by adding their respective addresses using #addTransportAddress(org.elasticsearch.common.transport.TransportAddress).

The transport client important modules used is the org.elasticsearch.transport.TransportModule which is started in client mode (only connects, no bind).
[中]传输客户端允许创建一个不属于集群的客户端,但只需使用#addTransportAddress(org.elasticsearch.common.transport.TransportAddress)添加一个或多个节点各自的地址,即可直接连接到一个或多个节点。
使用的传输客户端重要模块是组织。弹性搜索。运输以客户端模式启动的TransportModule(仅连接,不绑定)。

代码示例

代码示例来源:origin: brianfrankcooper/YCSB

Builder settings = Settings.settingsBuilder()
  .put("cluster.name", DEFAULT_CLUSTER_NAME)
  .put("node.local", Boolean.toString(!remoteMode))
  .put("path.home", pathHome);
 TransportClient tClient = TransportClient.builder().settings(settings).build();
 for (String h : nodeList) {
  String[] nodes = h.split(":");
  try {
   tClient.addTransportAddress(new InetSocketTransportAddress(
     InetAddress.getByName(nodes[0]),
     Integer.parseInt(nodes[1])
    client.admin().indices()
        .exists(Requests.indicesExistsRequest(indexKey)).actionGet()
        .isExists();
if (exists && newdb) {
 client.admin().indices().prepareDelete(indexKey).execute().actionGet();
client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet();

代码示例来源:origin: alibaba/canal

@Override
public void destroy() {
  if (transportClient != null) {
    transportClient.close();
  }
}

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

/**
 * Create the transport client
 * @return
 */
private Client createTransportClient() {
  final String clusterName = indexFig.getClusterName();
  final int port = indexFig.getPort();
  ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put( "cluster.name", clusterName )
    .put( "client.transport.sniff", true );
  String nodeName = indexFig.getNodeName();
  if ( "default".equals( nodeName ) ) {
    // no nodeName was specified, use hostname
    try {
      nodeName = InetAddress.getLocalHost().getHostName();
    }
    catch ( UnknownHostException ex ) {
      nodeName = "client-" + RandomStringUtils.randomAlphabetic( 8 );
      logger.warn( "Couldn't get hostname to use as ES node name, using {}", nodeName );
    }
  }
  settings.put( "node.name", nodeName );
  TransportClient transportClient = new TransportClient( settings.build() );
  // we will connect to ES on all configured hosts
  for ( String host : indexFig.getHosts().split( "," ) ) {
    transportClient.addTransportAddress( new InetSocketTransportAddress( host, port ) );
  }
  return transportClient;
}

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

@Override
public TransportClient createClient(Map<String, String> clientConfig) {
  Settings settings = Settings.settingsBuilder().put(clientConfig).build();
  TransportClient transportClient = TransportClient.builder().settings(settings).build();
  for (TransportAddress address : ElasticsearchUtils.convertInetSocketAddresses(transportAddresses)) {
    transportClient.addTransportAddress(address);
  }
  // verify that we actually are connected to a cluster
  if (transportClient.connectedNodes().isEmpty()) {
    // close the transportClient here
    IOUtils.closeQuietly(transportClient);
    throw new RuntimeException("Elasticsearch client is not connected to any Elasticsearch nodes!");
  }
  if (LOG.isInfoEnabled()) {
    LOG.info("Created Elasticsearch TransportClient with connected nodes {}", transportClient.connectedNodes());
  }
  return transportClient;
}

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

@Override
public TransportClient createClient(Map<String, String> clientConfig) {
  Settings settings = Settings.builder().put(clientConfig)
    .put(NetworkModule.HTTP_TYPE_KEY, Netty3Plugin.NETTY_HTTP_TRANSPORT_NAME)
    .put(NetworkModule.TRANSPORT_TYPE_KEY, Netty3Plugin.NETTY_TRANSPORT_NAME)
    .build();
  TransportClient transportClient = new PreBuiltTransportClient(settings);
  for (TransportAddress transport : ElasticsearchUtils.convertInetSocketAddresses(transportAddresses)) {
    transportClient.addTransportAddress(transport);
  }
  // verify that we actually are connected to a cluster
  if (transportClient.connectedNodes().isEmpty()) {
    // close the transportClient here
    IOUtils.closeQuietly(transportClient);
    throw new RuntimeException("Elasticsearch client is not connected to any Elasticsearch nodes!");
  }
  if (LOG.isInfoEnabled()) {
    LOG.info("Created Elasticsearch TransportClient with connected nodes {}", transportClient.connectedNodes());
  }
  return transportClient;
}

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

/**
 * Open client to elaticsearch cluster
 * 
 * @param clusterName
 */
private void openClient(String clusterName) {
 logger.info("Using ElasticSearch hostnames: {} ",
   Arrays.toString(serverAddresses));
 Settings settings = ImmutableSettings.settingsBuilder()
   .put("cluster.name", clusterName).build();
 TransportClient transportClient = new TransportClient(settings);
 for (InetSocketTransportAddress host : serverAddresses) {
  transportClient.addTransportAddress(host);
 }
 if (client != null) {
  client.close();
 }
 client = transportClient;
}

代码示例来源:origin: floragunncom/search-guard

final Settings settings = Settings.builder()
    .putList(ConfigConstants.SEARCHGUARD_AUTHCZ_REST_IMPERSONATION_USERS+".worf", "knuddel","nonexists")
    .build();
setup(settings);
final RestHelper rh = nonSslRestHelper();
    tc.admin().indices().create(new CreateIndexRequest("copysf")).actionGet();
    tc.index(new IndexRequest("vulcangov").type("kolinahr").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("starfleet_academy").type("students").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("starfleet_library").type("public").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("klingonempire").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("public").type("legends").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("spock").type("type01").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("kirk").type("type01").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("role01_role02").type("type01").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("starfleet","starfleet_academy","starfleet_library").alias("sf"))).actionGet();
    tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("klingonempire","vulcangov").alias("nonsf"))).actionGet();
    tc.admin().indices().aliases(new IndicesAliasesRequest().addAliasAction(AliasActions.add().indices("public").alias("unrestricted"))).actionGet();

代码示例来源:origin: floragunncom/search-guard

@Test
public void testTransportClientImpersonation() throws Exception {
  final Settings settings = Settings.builder()
      .putList("searchguard.authcz.impersonation_dn.CN=spock,OU=client,O=client,L=Test,C=DE", "worf", "nagilum")
      .build();
  setup(settings);
  try (TransportClient tc = getInternalTransportClient()) {
    tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
    ConfigUpdateResponse cur = tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[]{"config","roles","rolesmapping","internalusers","actiongroups"})).actionGet();
    Assert.assertEquals(clusterInfo.numNodes, cur.getNodes().size());
  }
  Settings tcSettings = Settings.builder()
      .put("searchguard.ssl.transport.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("spock-keystore.jks"))
      .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS,"spock")
      .put("path.home", ".")
      .put("request.headers.sg_impersonate_as", "worf")
      .build();
  try (TransportClient tc = getInternalTransportClient(clusterInfo, tcSettings)) {            
    NodesInfoRequest nir = new NodesInfoRequest();
    Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(nir).actionGet().getNodes().size());
  }
}

代码示例来源:origin: floragunncom/search-guard

tc.index(new IndexRequest("starfleet").type("ships").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"content\":1}", XContentType.JSON)).actionGet();
Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size());
CreateIndexResponse cir = tc.admin().indices().create(new CreateIndexRequest("vulcan")).actionGet();
Assert.assertTrue(cir.isAcknowledged());
IndexResponse ir = tc.index(new IndexRequest("vulcan").type("secrets").id("s1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"secret\":true}", XContentType.JSON)).actionGet();
Assert.assertTrue(ir.getResult() == Result.CREATED);
GetResponse gr =tc.prepareGet("vulcan", "secrets", "s1").setRealtime(true).get();
Assert.assertTrue(gr.isExists());
gr =tc.prepareGet("vulcan", "secrets", "s1").setRealtime(false).get();
Assert.assertTrue(gr.isExists());
SearchResponse actionGet = tc.search(new SearchRequest("vulcan").types("secrets")).actionGet();
Assert.assertEquals(1, actionGet.getHits().getHits().length);
System.out.println("------- 6 ---------");
gr =tc.prepareGet("searchguard", "sg", "config").setRealtime(false).get();
Assert.assertFalse(gr.isExists());
gr =tc.prepareGet("searchguard", "sg", "config").setRealtime(true).get();
Assert.assertFalse(gr.isExists());
actionGet = tc.search(new SearchRequest("searchguard")).actionGet();
Assert.assertEquals(0, actionGet.getHits().getHits().length);

代码示例来源:origin: brianfrankcooper/YCSB

final Builder settings = Settings.builder().put("cluster.name", DEFAULT_CLUSTER_NAME);
  final String key = (String) e.getKey();
  if (key.startsWith("es.setting.")) {
   settings.put(key.substring("es.setting.".length()), e.getValue());
  throw new IllegalArgumentException("unable to parse port [" + nodes[1] + "]", e);
 client.addTransportAddress(new InetSocketTransportAddress(address, port));
  client.admin().indices()
    .exists(Requests.indicesExistsRequest(indexKey)).actionGet()
    .isExists();
if (exists && newIndex) {
 client.admin().indices().prepareDelete(indexKey).get();
 client.admin().indices().create(
   new CreateIndexRequest(indexKey)
     .settings(
       Settings.builder()
         .put("index.number_of_shards", numberOfShards)
         .put("index.number_of_replicas", numberOfReplicas)
     )).actionGet();
client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet();

代码示例来源:origin: floragunncom/search-guard

tc.index(new IndexRequest("test").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"field2\":\"init\"}", XContentType.JSON)).actionGet();           
tc.index(new IndexRequest("lorem").type("type1").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source("{\"field2\":\"init\"}", XContentType.JSON)).actionGet();      
WhoAmIResponse wres = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet();   
System.out.println(wres);
Assert.assertEquals("CN=kirk,OU=client,O=client,L=Test,C=DE", wres.getDn());
  tc.admin().indices().putMapping(new PutMappingRequest("test").type("typex").source("fieldx","type=text")).actionGet();
  Assert.fail();
} catch (ElasticsearchSecurityException e) {
  tc.admin().cluster().reroute(new ClusterRerouteRequest()).actionGet();
  Assert.fail();
} catch (ElasticsearchSecurityException e) {
WhoAmIResponse wres = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet();                
Assert.assertEquals("CN=spock,OU=client,O=client,L=Test,C=DE", wres.getDn());
Assert.assertFalse(wres.isAdmin());

代码示例来源:origin: floragunncom/search-guard

tc.addTransportAddress(new TransportAddress(new InetSocketAddress(info.nodeHost, info.nodePort)));
Assert.assertEquals(info.numNodes,
    tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size());
  tc.admin().indices().create(new CreateIndexRequest("searchguard")).actionGet();
} catch (Exception e) {
  tc.index(ir).actionGet();
    .execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(ConfigConstants.CONFIG_NAMES.toArray(new String[0])))
    .actionGet();
Assert.assertEquals(info.numNodes, cur.getNodes().size());
SearchResponse sr = tc.search(new SearchRequest("searchguard")).actionGet();
sr = tc.search(new SearchRequest("searchguard")).actionGet();
Assert.assertTrue(tc.get(new GetRequest("searchguard", "sg", "config")).actionGet().isExists());
Assert.assertTrue(tc.get(new GetRequest("searchguard","sg","internalusers")).actionGet().isExists());
Assert.assertTrue(tc.get(new GetRequest("searchguard","sg","roles")).actionGet().isExists());
Assert.assertTrue(tc.get(new GetRequest("searchguard","sg","rolesmapping")).actionGet().isExists());
Assert.assertTrue(tc.get(new GetRequest("searchguard","sg","actiongroups")).actionGet().isExists());
Assert.assertFalse(tc.get(new GetRequest("searchguard","sg","rolesmapping_xcvdnghtu165759i99465")).actionGet().isExists());
Assert.assertTrue(tc.get(new GetRequest("searchguard","sg","config")).actionGet().isExists());

代码示例来源:origin: larsga/Duke

private void setupConnection() {
  ImmutableSettings.Builder settings = ImmutableSettings
      .settingsBuilder();
  settings.put("cluster.name", this.cluster);
        f.mkdirs();
      settings.put("path." + sub, subdir);
      settings.put("index.store.type", "memory");
    settings.put("client.transport.sniff", this.clientSniff);
    this.client = new TransportClient(settings.build());
          .addTransportAddress(new InetSocketTransportAddress(
              hostname, hostport));
  ClusterHealthResponse actionGet = this.client.admin().cluster()
      .prepareHealth().setWaitForYellowStatus().execute().actionGet();
  System.out.println("ElasticSearch Health Check " + actionGet);

代码示例来源:origin: Impetus/Kundera

Builder builder = Settings.settingsBuilder();
builder.put("client.transport.sniff", true);
  builder.put(properties);
Settings settings = builder.build();
TransportClient client = TransportClient.builder().settings(settings).build();
  client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(h, new Integer(port))));

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

@Override
public void recreateIndex(String indexName)
  throws IOException {
 DeleteIndexRequestBuilder dirBuilder = transportClient.admin().indices().prepareDelete(indexName);
 try {
  DeleteIndexResponse diResponse = dirBuilder.execute().actionGet();
 } catch (IndexNotFoundException ie) {
  System.out.println("Index not found... that's ok");
 }
 CreateIndexRequestBuilder cirBuilder = transportClient.admin().indices().prepareCreate(indexName);
 CreateIndexResponse ciResponse = cirBuilder.execute().actionGet();
 Assert.assertTrue(ciResponse.isAcknowledged(), "Create index succeeeded");
}

代码示例来源:origin: floragunncom/search-guard

@Test
public void testTransportClientImpersonationWildcard() throws Exception {
  final Settings settings = Settings.builder()
      .putList("searchguard.authcz.impersonation_dn.CN=spock,OU=client,O=client,L=Test,C=DE", "*")
      .build();
  setup(settings);
  Settings tcSettings = Settings.builder()
      .put("searchguard.ssl.transport.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("spock-keystore.jks"))
      .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS,"spock")
      .put("path.home", ".")
      .put("request.headers.sg_impersonate_as", "worf")
      .build();
  try (TransportClient tc = getInternalTransportClient(clusterInfo, tcSettings)) {
    NodesInfoRequest nir = new NodesInfoRequest();
    Assert.assertEquals(clusterInfo.numNodes, tc.admin().cluster().nodesInfo(nir).actionGet().getNodes().size());
  }        
}

代码示例来源:origin: loklak/loklak_server

/**
 * create a elasticsearch transport client (remote elasticsearch)
 * @param addresses an array of host:port addresses
 * @param clusterName
 */
public ElasticsearchClient(final String[] addresses, final String clusterName) {
  // create default settings and add cluster name
  Settings.Builder settings = Settings.builder()
      .put("cluster.name", clusterName)
      .put("cluster.routing.allocation.enable", "all")
      .put("cluster.routing.allocation.allow_rebalance", "true");
  // create a client
  TransportClient tc = TransportClient.builder()
      .settings(settings.build())
      .build();
  for (String address: addresses) {
    String a = address.trim();
    int p = a.indexOf(':');
    if (p >= 0) try {
      InetAddress i = InetAddress.getByName(a.substring(0, p));
      int port = Integer.parseInt(a.substring(p + 1));
      tc.addTransportAddress(new InetSocketTransportAddress(i, port));
    } catch (UnknownHostException e) {
      DAO.severe(e);
    }
  }
  this.elasticsearchClient = tc;
}

代码示例来源:origin: brianfrankcooper/YCSB

private void refreshIfNeeded() {
 if (isRefreshNeeded) {
  final boolean refresh;
  synchronized (this) {
   if (isRefreshNeeded) {
    refresh = true;
    isRefreshNeeded = false;
   } else {
    refresh = false;
   }
  }
  if (refresh) {
   client.admin().indices().refresh(new RefreshRequest()).actionGet();
  }
 }
}

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

@Override
  public Client get() {

    Settings settings = Settings.builder()
        .put("client.transport.ignore_cluster_name", true)
        .put("client.transport.sniff", true)
        .build();

    TransportClient tc = new PreBuiltTransportClient(settings);

    List<URI> clusterAddresses = configuration.getURIs();

    if (clusterAddresses.isEmpty()) {
      logger.warn(ElasticSearchConfiguration.ELASTIC_SEARCH_URL_PROPERTY_NAME +
          " is not set.  Indexing will remain DISABLED.");
    }
    for (URI hostAddress : clusterAddresses) {
      int port = Optional.ofNullable(hostAddress.getPort()).orElse(9200);
      try {
        tc.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostAddress.getHost()), port));
      } catch (UnknownHostException uhe){
        throw new ProvisionException("Invalid host" + hostAddress.getHost(), uhe);
      }
    }
    return tc;
  }
}

代码示例来源:origin: prestodb/presto

private String[] getIndices(TransportClient client, GetIndexRequest request)
{
  try {
    return retry()
        .maxAttempts(maxAttempts)
        .exponentialBackoff(maxRetryTime)
        .run("getIndices", () -> client.admin()
            .indices()
            .getIndex(request)
            .actionGet(requestTimeout.toMillis())
            .getIndices());
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}

相关文章

微信公众号

最新文章

更多