Spring Boot:与 Kafka 的 Rest 端点集成

Spring Boot:与 Kafka 的 Rest 端点集成

问题描述:

在必须向另一个服务发送消息以进行处理的休息端点上工作.它是一个微服务架构,所有服务都通过Kafka消息代理连接.

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 支持 @Async 用于异步方法,但它没有按预期工作.代码类似于

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);
}

它不会等待消息从 kafka 返回.

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

这里缺少什么?

尝试使用sync(blocking)方法发送消息producer.send(id).get();这将使执行等待结果.

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