問題:在ElasticSearch6.3.2開啓x-pack後如何使用java客戶端訪問?
ElasticSearch6.3.2 java客戶端調用
這裏引入的是spring-boot-starter-data-elasticsearch(底層用的也是TransportClient)
開啓x-pack後需要用到x-pack-transport(官網文檔版本是6.2.4-這裏有詳細介紹)
ElasticSearch6.3版本已經安裝了x-pack x-pack默認已經安裝位置
/usr/local/software/elasticsearch-6.3.2/modules
license時間是一個月
curl -XGET -u elastic:ilikees2019 'http://127.0.0.1:9200/_license'
集成過程記錄如下:
1、pom.xml文件
這裏使用springboot版本是2.1.3.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--spring data 操作es-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--add the x-pack 及依賴 開始-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-core</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.65</version>
</dependency>
<!--add the x-pack 及依賴 結束-->
x-pack-core.jar可以從/usr/local/software/elasticsearch-6.3.2/modules/x-pack/x-pack-core/x-pack-core-6.3.2.jar 下載到本地maven庫中
其他依賴與安全認證的算法包如bouncycastle等也需要自己引入下
2、創建XPackClient
@Bean
public TransportClient getTransportClient() throws UnknownHostException{
Settings.Builder builder = Settings.builder();
builder.put("cluster.name", "myClusterName");//集羣名稱
builder.put("client.transport.sniff", true);//自動嗅探整個集羣的狀態,把集羣中其他ES節點的ip添加到本地的客戶端列表中
builder.put("xpack.security.transport.ssl.enabled", false);//設置xpack ssl這裏設置爲false
builder.put("xpack.security.user", "xxxxx");//集羣設置的密碼
builder.build()
TransportClient transportClient = new PreBuiltXPackTransportClient(settings())
.addTransportAddress(new TransportAddress(InetAddress.getByName("xxxxx"), 9300));//集羣的ip地址
log.info("transportClient.listedNodes():{}",transportClient.listedNodes());
log.info("ElasticsearchXPackClient 啓動成功");
return transportClient;
}
3、測試使用
因爲上面pom.xml文件中用的是spring-boot-starter-data-elasticsearch 所以也可以直接使用ElasticsearchRepository,最後調用的還是配置的TransportClient
@Autowired
private TransportClient transportClient;
@Test
public void testFindEsTransport() {
// 發起請求得到響應
GetResponse response=transportClient.prepareGet("bank","account","9").get();
System.out.println(response.getSource());
}