public class
Elasticseach {
TransportClient
client
=
null
;
public
Elasticseach(){
//根据官方文档得知,如果集群名称改变,则在设置中设成配置文件里上设置的名字
Settings settings = Settings.
builder
()
.put(
"cluster.name"
,
"cluemining_es_cluester"
).build();
//在linux 中elasticsearch/bin/config/elasticseach.yml 中设置集群名称
try
{
//我用的是5.5.2版本,该版本与最新的6系列连接方式不同
client
=
new
PreBuiltTransportClient(Settings.
EMPTY
)
.addTransportAddress(
new
InetSocketTransportAddress(InetAddress.
getByName
(
"10.0.0.42"
),
9900
))
.addTransportAddress(
new
InetSocketTransportAddress(InetAddress.
getByName
(
"10.0.0.42"
),
9901
))
.addTransportAddress(
new
InetSocketTransportAddress(InetAddress.
getByName
(
"10.0.0.42"
),
9902
));
SearchResponse response =
client
.prepareSearch().get();
System.
out
.println(response);
}
catch
(UnknownHostException e) {
e.printStackTrace();
}
finally
{
client
.close();
}
}
public
TransportClient getConnection(){
if
(
client
==
null
) {
synchronized
(Elasticseach.
class
) {
if
(
client
==
null
) {
new
Elasticseach();
}
}
}
return
client
;
}
}
注:mavan导elasticsearch时可能会出现依赖冲突,既
org.elasticsearch.client
包中的netty4可能因版本问题出现java.lang.AbstractMethodError: org.elasticsearch.transport.TcpTransport.sendMessage问题
解决方法:将netty版本改成elasticsearch跟包一致,如下所示
<
dependency
>
<
groupId
>
org.elasticsearch.client
groupId
>
<
artifactId
>
transport
artifactId
>
<
version
>
5.5.2
version
>
<
exclusions
>
<
exclusion
>
<
artifactId
>
transport-netty4-client
artifactId
>
<
groupId
>
org.elasticsearch.plugin
groupId
>
exclusion
>
<
exclusion
>
<
artifactId
>
elasticsearch
artifactId
>
<
groupId
>
org.elasticsearch
groupId
>
exclusion
>
exclusions
>
dependency
>
<
dependency
>
<
groupId
>
org.elasticsearch.plugin
groupId
>
<
artifactId
>
transport-netty4-client
artifactId
>
<
version
>
5.5.2
version
>
dependency
>