PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

如何使用Java构建Elasticsearch客户端并调用API?

WBOY
WBOY 转载
2023-04-24 09:46:06 497浏览

    elasticsearch通过构造一个client对外提供了一套丰富的java调用接口。总体来说client分为两类cluster信息方面的client及数据(index)方面的client。这两个大类由可以分为通用操作和admin操作两类。

    client的继承关系

    (1.5版本,其它版本可能不一样):

    elasticsearch怎么构造Client实现java客户端调用接口

    通过这个继承关系图可以很清楚的了解client的实现,及功能。总共有三类即client, indicesAdminClient和ClusterAdminClient。它都有自己的实现类,但最后都是通过client接口对外提供服务。client作为对外的总接口,首先通过admin()方法组合了admin的相关操作,它本身也提供了所有对数据和cluster的通用操作。

    方法实现上

    所有的接口都通过两种方式实现了异步调用,一个是返回一个ActionFuture,另外一种方式是接受一个ActionListener。

    以index方法为例

    如下所示

     ActionFuture  index(IndexRequest request) ;

     void index(IndexRequest request, ActionListener listener);

    第一个方法会返回一个future,第二个方法则需要传递一个Listener。这也是异步实现的两个基本方式。client使用了门面模式,所有的实现都在AbstractClient类中,还以index方法为例,代码如下所示:

    @Override
        public ActionFuture index(final IndexRequest request) {
            return execute(IndexAction.INSTANCE, request);
        }
        @Override
        public void index(final IndexRequest request, final ActionListener listener) {
            execute(IndexAction.INSTANCE, request, listener);
        }

    实现如上所示,之所以说它是门面模式是因为所有的方法都被集成到了client中,但是执行过程都是在对应的action中执行。在execute方法中,获取到相应的action实例,真正的逻辑是在对应的transportaction中实现。

    execute方法代码

    如下所示:

    @SuppressWarnings("unchecked")
        @Override
        public > ActionFuture execute(Action action, Request request) {
            headers.applyTo(request);
            TransportAction transportAction = actions.get((ClientAction)action);
            return transportAction.execute(request);
        }
        @SuppressWarnings("unchecked")
        @Override
        public > void execute(Action action, Request request, ActionListener listener) {
            headers.applyTo(request);
            TransportAction transportAction = actions.get((ClientAction)action);
            transportAction.execute(request, listener);
        }

    每一种操作都对应有相应的transportAction,这些transportAction才是最终的执行者。这里先以index为例简单说明,在后面索引功能分析中会看到更多这种的结果。

    public class IndexAction extends ClientAction {
        public static final IndexAction INSTANCE = new IndexAction();
        public static final String NAME = "indices:data/write/index";
        private IndexAction() {
            super(NAME);
        }
        @Override
        public IndexResponse newResponse() {
            return new IndexResponse();
        }
        @Override
        public IndexRequestBuilder newRequestBuilder(Client client) {
            return new IndexRequestBuilder(client);
        }
    }

    在IndexAction中只是简单的定义了一个NAME,及几个简单的方法。这个名字会在启动时作为对于的transportHandler的key注册到TransportService中。在execute方法中,会根据action的将transportAction取出如上一段代码所示。真正的执行逻辑在InternalTransportClient中,这里先略过它的实现,后面会有详细分析。所有这些action的注册都是在actionModule中实现,注册过程会在后面跟action一起分析。

    以上就是如何使用Java构建Elasticsearch客户端并调用API?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除