How to Convert callback to a Promise

2019-03-02 02:03发布

I am using play framework and Apache Kafka.

I have a POST method which sends a message to Kafka. Kafka has an API method

public java.util.concurrent.Future send(ProducerRecord record, Callback callback)

of which the Javadoc says

Asynchronously send a record to a topic and invoke the provided callback when the send has been acknowledged.

I am exposing this functionality using the play framework. I want to return a Promise<Result> from the Controller method but can't figure out how to implement this in a non-blocking way. Can someone help me with this?

1条回答
太酷不给撩
2楼-- · 2019-03-02 02:19

After some searching found the answer with some help from this one.

Following is the code

RedeemablePromise<Result> promise = RedeemablePromise.empty();

kafkaProducer.send(record, (metadata, ex) -> {
    if (ex != null) {
        promise.failure(ex);
    } else {
        promise.success(created(Json.toJson(new ProduceResult())));
    }
});
查看更多
登录 后发表回答