elasticsearch for java 认证连接

环境

服务器:centos6
elasticsearch:5+
java:1.8
工具:CRT

步骤

刚开始我是参照官网的来:

Transport Client

代码如下:

package elasticsearch.estutorial;

//import 省略。。。

public class EsUtils {

    public static TransportClient connectionEs(){

        //设置集群的名字
        Settings settings = Settings.builder().put("cluster.name", "yutao")
                .put("client.transport.sniff", true)
                .build();

        /*//忽视连接集群时名字验证
        builder.put("client.transport.ignore_cluster_name", true);
        //ping 一个节点时等待时间 默认5秒
        builder.put("client.transport.ping_timeout", "5s");
        //多久采样 ping / 节点列表和连接
        builder.put("client.transport.nodes_sampler_interval", "5s");*/

        try {
            //连接
            @SuppressWarnings("resource")
            TransportClient client = new PreBuiltTransportClient(settings)
                                         .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.116.131"), 9300));
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void indexApi(){
        TransportClient client = connectionEs();
        String json = "{" +
                "\"user\":\"kimchy\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
            "}";

        List connectedNodes = client.connectedNodes();
        System.out.println(connectedNodes);


        IndexResponse response = client.prepareIndex("twitter", "tweet").setSource(json, XContentType.JSON).get();

        String index = response.getIndex();
        String type = response.getType();

        String id = response.getId();

        long version = response.getVersion();

        RestStatus status = response.status();

        System.out.println(index);
        System.out.println(type);
        System.out.println(id);
        System.out.println(version);
        System.out.println(status);

    }
}

main方法:

public static void main( String[] args )
    {
        EsUtils.indexApi();
        System.out.println( "Hello World!" );
    }

这个时候,它总是报,类似下面的错误:

Exception in thread "main" NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{hbw6d5KVQ5KJZT2rK3Oz-A}{192.168.116.131}{192.168.116.131:9300}]]
    at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:347)
    at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:245)
    at org.elasticsearch.client.transport.TransportProxyClient.execute(TransportProxyClient.java:59)
    at org.elasticsearch.client.transport.TransportClient.doExecute(TransportClient.java:363)
    at org.elasticsearch.client.support.AbstractClient.execute(AbstractClient.java:408)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:80)
    at org.elasticsearch.action.ActionRequestBuilder.execute(ActionRequestBuilder.java:54)
    at org.elasticsearch.action.ActionRequestBuilder.get(ActionRequestBuilder.java:62)
    at elasticsearch.estutorial.EsUtils.indexApi(EsUtils.java:63)
    at elasticsearch.estutorial.App.main(App.java:11)

网上的说法,就是:
①假设你改了集群的名字的话,代码里就要指定集群名称
②假设你指定了ip了,代码里同样也需要指定
③端口要使用9300

关键是上面三点我都做到了,可是还是不行。

后来猛然一想,9300的端口好像没有开放。

执行如下命令后,开放9300端口:

[yutao@localhost config]$ sudo firewall-cmd --permanent --add-port=9300/tcp
success
[yutao@localhost config]$ sudo firewall-cmd --reload
success
[yutao@localhost config]$ 
[yutao@localhost config]$ 
[yutao@localhost config]$ 
[yutao@localhost config]$ sudo firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens33
  sources: 
  services: dhcpv6-client http ssh
  ports: 7080/tcp 8080/tcp 9200/tcp 9300/tcp 9100/tcp 6379/tcp 5601/tcp
  protocols: 
  masquerade: no
  forward-ports: 
  sourceports: 
  icmp-blocks: 
  rich rules: 

接着在执行代码,报错了,不过是另外一个错:

java missing authentication token for action [cluster:monitor/state]

这个错,错非常明显,因为我安装了x-pack,所以需要认证:

网上搜索了一番:

X-Pack for the Elastic Stack

installing_xpackclient

Java Client and Security

引入 xpackclient

...>

   
      
      
         elasticsearch-releases
         https://artifacts.elastic.co/maven
         
            true
         
         
            false
         
      
      ...
   
   ...

   
      
      
         org.elasticsearch.client
         x-pack-transport
         5.6.4
      
      ...
   
   ...

 

使用类:PreBuiltXPackTransportClient

之后代码里使用PreBuiltXPackTransportClient,而不是PreBuiltTransportClient

public static TransportClient connectionEs(){

        //设置集群的名字
        Settings settings = Settings.builder().put("cluster.name", "yutao")
                .put("client.transport.sniff", true)
                .put("xpack.security.transport.ssl.enabled", false)
                .put("xpack.security.user", "elastic:changeme").build();

        /*//忽视连接集群时名字验证
        builder.put("client.transport.ignore_cluster_name", true);
        //ping 一个节点时等待时间 默认5秒
        builder.put("client.transport.ping_timeout", "5s");
        //多久采样 ping / 节点列表和连接
        builder.put("client.transport.nodes_sampler_interval", "5s");*/

        try {
            //连接
            @SuppressWarnings("resource")
//          TransportClient client = new PreBuiltTransportClient(settings)
//                                       .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.116.131"), 9300));

            TransportClient client = new PreBuiltXPackTransportClient(settings)
             .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.116.131"), 9300));
            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

这样就可以啦!

就我的测试项目而言,执行后的结果为:

no modules loaded
loaded plugin [org.elasticsearch.index.reindex.ReindexPlugin]
loaded plugin [org.elasticsearch.join.ParentJoinPlugin]
loaded plugin [org.elasticsearch.percolator.PercolatorPlugin]
loaded plugin [org.elasticsearch.script.mustache.MustachePlugin]
loaded plugin [org.elasticsearch.transport.Netty3Plugin]
loaded plugin [org.elasticsearch.transport.Netty4Plugin]
loaded plugin [org.elasticsearch.xpack.XPackPlugin]
[{ONRkJ5J}{ONRkJ5JxTH6Ic_E_sKhNAg}{4C0l5X7uQfShFJPj8pcXYQ}{192.168.116.131}{192.168.116.131:9300}{ml.max_open_jobs=10, ml.enabled=true}]
twitter
tweet
AWASSMU-4Wy1PJFus9gf
1
CREATED
Hello World!

好了,基础而已;

参考地址:

https://www.elastic.co/guide/en/x-pack/5.6/api-java.html#_installing_xpackclient

https://www.elastic.co/guide/en/x-pack/current/java-clients.html#java-clients

https://www.elastic.co/guide/en/x-pack/current/index.html

你可能感兴趣的:(Java,es库,elasticsearch)