gpt4 book ai didi

java - ListenableFuture - 返回前如何等待

转载 作者:行者123 更新时间:2023-11-30 02:31:21 26 4
gpt4 key购买 nike

我有一个 Spring Cloud 微服务,它在 Kafka 代理上发布消息,该微服务可通过 REST API 访问。

我想将提交状态返回给调用者,但似乎 Java 不等待。如何使其在我的代码返回之前等待成功或失败?

代码如下:

kafkaProduc.send("topictest", msg).addCallback(
new ListenableFutureCallback<SendResult<String, ExecutionDataMessage>>() {
@Override
public void onSuccess(SendResult<String, ExecutionDataMessage> result) {
eresp.status = "ok";
eresp.msg = "message submitted successfully";
}

@Override
public void onFailure(Throwable ex) {
eresp.status = "error";
eresp.msg = "failure while sending data to kafka. exception: " + ex.getMessage();
}
});
HttpStatus erespStatus = eresp.status == "ok" ? HttpStatus.CREATED : HttpStatus.BAD_REQUEST;
return new ResponseEntity<ExecutionResponse>(eresp, erespStatus);

最佳答案

回调用于当您想要异步结果时。如果要阻止调用线程,请使用 future.get()...

ListenableFuture<SendResult<String, String>> future = template.send("foo", "bar");
try {
SendResult<String, String> sendResult = future.get(10, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Thread.currentThread.interrupt();
}
catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

关于java - ListenableFuture - 返回前如何等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44209130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com