我正在使用 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/