java - 使用 Elasticsearch 的 Java High Level Rest Client 收到异步请求的响应后立即返回某些内容

标签 java rest elasticsearch

我正在使用 Elasticsearch 的 Java 高级 Rest 客户端,我希望 createProfileDocument 方法在收到异步请求响应后立即返回某些内容(就好像 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();
}

最佳答案

两个选项: 切换到同一调用的同步版本

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

或者如果您想继续使用异步版本。您可以在package org.elasticsearch.action.support;

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

关于java - 使用 Elasticsearch 的 Java High Level Rest Client 收到异步请求的响应后立即返回某些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672385/

相关文章:

python - Elasticsearch Kibana TimeStamp key 丢失

java - Hibernate + spring 版本兼容性

java - 尝试使用原始套接字发送 GET 请求时收到 301

java - 如何在我的 ant 构建中包含本地依赖项

html - 使用 Blogger API 获取的帖子数量限制(错误 400)

java - 在restTemplate之后设置 Spring 过滤器

elasticsearch - 使用 Elasticsearch 的关键字搜索

java - 如何让 KeyListener 使用主线程而不是 EDT?

spring-boot - 关于 ResponseStatusException 返回错误对象中的空消息字段

Elasticsearch 基数聚合给出完全错误的结果