Elasticsearch增長X-Pack插件後如何使用Java客戶端訪問

Elasticsearch沒有安裝X-Pack插件時建立TransportClient只須要依賴java

<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>transport</artifactId>
  <version>5.3.0</version>
</dependency>

而後使用elasticsearch

Settings settings = Settings.builder()
        .put("cluster.name", "myClusterName").build();

TransportClient client = new PreBuiltTransportClient(settings)
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host1"), 9300))
        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));

// on shutdown
client.close();

就能鏈接上Elasticsearch了maven

可是在增長了X-Pack插件以後,因爲Elasticsearch默認開啓了xpack.security.enabled,若是仍是使用原先的鏈接方式的話會拋權限異常,解決方式有兩種ui

1.直接在elasticsearch.yml中增長配置url

xpack.security.enabled=false

這樣的話就仍是能夠使用原先的方式進行訪問插件

2.使用x-pack-transportcode

<dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>x-pack-transport</artifactId>
  <version>5.3.0</version>
</dependency>

注意這個依賴在maven中央倉庫中找不到xml

須要在pom.xml中配置elastic的maven倉庫get

<repository>
  <id>elastic</id>
  <url>https://artifacts.elastic.co/maven</url>
  <releases>
     <enabled>true</enabled>
  </releases>
  <snapshots>
     <enabled>false</enabled>
  </snapshots>
</repository>

下載好依賴以後使用如下方式就能訪問了it

TransportClient client = new PreBuiltXPackTransportClient(Settings.builder()
        .put("cluster.name", "myClusterName")
        .put("xpack.security.user", "transport_client_user:changeme")
        ...
        .build())
    .addTransportAddress(new InetSocketTransportAddress("localhost", 9300))
    .addTransportAddress(new InetSocketTransportAddress("localhost", 9301));
相關文章
相關標籤/搜索