使用Elasticsearch的Java高级Rest客户端在收到对异步请求的响应后立即返回内容

时间:2019-02-13 14:19:34

标签: java rest elasticsearch

我正在使用Elasticsearch的Java High Level Rest Client,我希望createProfileDocument方法在收到对Async请求的响应后立即返回某些内容(就像return语句在onResponse方法内部)一样,我已经做到了解决(下面的代码),但是我相信有更好的方法可以做到这一点,我在文档中没有找到。这是我的代码:

private IndexResponse response = null;

public String createProfileDocument(ProfileDocument document) throws Exception {
    UUID uuid = UUID.randomUUID();
    document.setId(uuid.toString());
    IndexRequest indexRequest = new IndexRequest("profiles", "doc", document.getId())
            .source(convertProfileDocumentToMap(document));
    ActionListener<IndexResponse> listener;
    listener = new ActionListener<IndexResponse>() {
        @Override
        public void onResponse(IndexResponse indexResponse) {
            response = indexResponse;
            //I want it to behave as if the return statement was here
        }

        @Override
        public void onFailure(Exception e) {
            e.printStackTrace();
        }
    };
    client.indexAsync(indexRequest, RequestOptions.DEFAULT, listener);
    //waiting for response, shouldn't be done this way
    while (response == null) {

    }
    IndexResponse responseClone = response;
    response = null;
    return responseClone.getResult().name().toString();
}

2 个答案:

答案 0 :(得分:1)

两个选项: 切换到同一通话的同步版本

IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);

或者如果您想继续使用异步版本。您可以在PlainActionFuture

中使用package org.elasticsearch.action.support;
PlainActionFuture<IndexResponse> future = new PlainActionFuture<>();
client.indexAsync(indexRequest, RequestOptions.DEFAULT, future);
IndexResponse response = future.actionGet();

答案 1 :(得分:0)

我更喜欢异步请求,尤其是对于长时间运行的工作(例如,重新索引)。异步方式可以更轻松地处理故障。这是一个示例:

    PlainActionFuture<BulkByScrollResponse> future = new PlainActionFuture<>();
    restHighLevelRestClientHelper.reindex(INDEX_NAME, NEW_INDEX_NAME, future);
    try {
        // onResponse
        if (future.isDone()) {
            // Set 1 hour as the limit, if time out throw exception.
            BulkByScrollResponse response = future.actionGet(TimeValue.timeValueMinutes(60));
            System.out.println("The request took " + response.getTook());
        } else {
            // onFailure
            throw new Exception("Something wrong with the ES query.");
        }
    } catch(Exception e) {
        throw new Exception("The request timed out.");
    }