Spring Boot:与Kafka的其余端点集成
问题描述:
正在其余端点上工作,该端点必须将消息发送到另一个服务进行处理.这是一个微服务架构,所有服务都通过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.