Elasticsearch没有安装X-Pack插件时创建TransportClient只需要依赖
org.elasticsearch.client
transport
5.3.0
然后使用
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了
但是在增加了X-Pack插件之后,由于Elasticsearch默认开启了xpack.security.enabled,如果还是使用原先的连接方式的话会抛权限异常,解决方式有两种
1.直接在elasticsearch.yml中增加配置
xpack.security.enabled=false
这样的话就还是可以使用原先的方式进行访问
2.使用x-pack-transport
org.elasticsearch.client
x-pack-transport
5.3.0
注意这个依赖在maven中央仓库中找不到
需要在pom.xml中配置elastic的maven仓库
elastic
https://artifacts.elastic.co/maven
true
false
下载好依赖之后使用以下方式就能访问了
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));