KAFKA ListenableFuture spring-如何根据 onsuccess 方法 future.addCallback 返回客户端响应对象,因为 onsuccess 为 void

问题描述 投票:0回答:2
public class Test {

    public StudentDto publishStudentDto

    {
        ListenableFuture<SendResult<String, Student>> future = this.studentKafkaTemplate.send(topicName, student);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Student>>() {
            @Override
            public void onSuccess(SendResult<String, Student> result) {
                logger.info("Student created & message published to topic: {} with offset: {} to partition {}", student, result.getRecordMetadata().offset(), result.getRecordMetadata().partition());
            }

            @Override
            public void onFailure(Throwable ex) {
                logger.error("student not created. Error in publishing student to topic : " + student, ex);
            }
        });
    }
}

如果 Student 在主题上成功发布,我想将 StudentDto 返回给控制器。但由于 onSuccess 是在响应返回到控制器之后调用的。如果发布成功,有什么办法可以将 StudentD 返回给我吗?

如果 Student 在主题上成功发布,我想将 StudentDto 返回给控制器。但由于 onSuccess 是在响应返回到控制器之后调用的。如果发布成功,有什么办法可以将 StudentD 返回给我吗?

java spring-boot apache-kafka spring-kafka kafka-producer-api
2个回答
0
投票

不要使用异步侦听器,只需在未来调用

get(...)
(有一定的超时),线程将阻塞,直到成功或失败。


0
投票
future.completable().join();

通过使用上面这行代码和一个用于更新状态的小标志,主线程将等待回调完成后再退出,您可以比较标志来返回或离开它。

join() 返回 future 完成后的结果。

© www.soinside.com 2019 - 2024. All rights reserved.