Spring Boot: Rest endpoint integration with Kafka

2019-07-24 23:51发布

问题:

Working on a rest endpoint which has to send a message to another service to process. It is a microservice architecture and all the services are connected via Kafka message broker.

Spring supports @Async for asynchronous methods but it doesn't work as expected. Code is something like

@RequestMapping(method = RequestMethod.GET, value = "/responses/{id}", produces = "application/json")
@Async
public CompletableFuture<Response> getResponseById(@PathVariable @Valid Long id) {
  //some code
  producer.send(id);
  //other service will send the response back and kafka consumer will save it to the db
  responseRepository.findById(id);
}

It doesn't wait for the message to come back from kafka.

What is missing here?

回答1:

Try to use sync(blocking) method to send message producer.send(id).get(); This will make execution wait for the result.