ListenableFuture - 返回前如何等待

Ale*_*dre 6 java spring-boot spring-kafka

我有一个 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);
Run Code Online (Sandbox Code Playgroud)

Gar*_*ell 4

回调用于当您想要异步结果时。如果您想阻止调用线程,请使用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();
}
Run Code Online (Sandbox Code Playgroud)