es装了x-pack权限工具以后,java(maven项目)访问es也需要相应的调整。按照官网给的教程:
首先,pom.xml增加
<project ...>
<repositories>
<!-- add the elasticsearch repo -->
<repository>
<id>elasticsearch-releases</id>
<url>https://artifacts.elastic.co/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
...
</repositories>
...
<dependencies>
<!-- add the x-pack jar as a dependency -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>x-pack-transport</artifactId>
<version>{version}</version>
</dependency>
...
</dependencies>
...
</project>
很多人发现,在这步的时候x-pack-transport依赖根本下载不下来,会报找不到类。
比如:
Caused by: java.lang.ClassNotFoundException: org.elasticsearch.xpack.XPackPlugin
解决办法:
查看maven的settings.xml文件
把mirrorOf标签里的内容改成*,!elasticsearch-releases(与pom.xml的repository id同名)。
配置成*表示所有的依赖都只会在配置的这个url找。加!elasticsearch-releases表示除了elasticsearch-releases的依赖其他依赖都在这个url找。
<mirror>
<id>central</id>
<mirrorOf>*,!elasticsearch-releases</mirrorOf>
<name>Human Readable Name for this Mirror</name>
<url>http://192.168.3.18:9096/nexus/content/groups/public/</url>
</mirror>
还有另一种办法就是修改settings.xml的profile(推荐)。
修改settings.xml如下:
<mirrors>
<mirror>
<id>central</id>
<mirrorOf>central</mirrorOf><!-- 修改此处 -->
<name>Human Readable Name for this Mirror</name>
<url>http://192.168.3.18:9096/nexus/content/groups/public/</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>central-repos</id>
<repositories>
...
<repository> <!-- 增加elastic仓库 -->
<id>elasticsearch-releases</id>
<url>https://artifacts.elastic.co/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
...
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>central-repos</activeProfile> <!-- 激活 -->
</activeProfiles>
然后就可以把pom.xml文件里的repositories代码删掉。
接着是官网的Java代码:
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;
...
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));
本来以为这次完美了,结果跑起来以后报了底下这个错误。
Caused by: java.lang.IllegalArgumentException: unknown setting [xpack.security.transport.ssl.enabled] please check that any required plugins are installed, or check the breaking changes documentation for removed settings
粗心啊!要用x-pack插件就不能用PreBuiltTransportClient来实例化client了,把PreBuiltTransportClient换成PreBuiltXPackTransportClient就搞定了。