REST 端点:不返回值的异步执行



我的问题可能很容易解决,但我现在不明白。在我的Quarkus-App中,我有一个REST-Endpoint,它应该调用一个方法,不要等待结果并立即返回202-HTTP-Statuscode。

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response calculateAsync(String input) {
process();
return Response.accepted().build();
}

我已经阅读了关于 Vert.x 和异步处理的 Quarkus-Documentation 。但重点是:处理是异步完成的,但客户端等待结果。我的客户端不需要等待,因为没有返回值。这有点像批处理的调用。

所以我需要类似new Thread的东西,但要包含所有的夸库斯语境。

我们找到了一个解决方案:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response calculateAsync(String input) {
Uni.createFrom().item(input).emitOn(Infrastructure.getDefaultWorkerPool()).subscribe().with(
item -> process(input), Throwable::printStackTrace
);
return Response.accepted().build();
}

您可以在参数中使用@Suspended AsyncResponse response并使方法返回void下面是类似方法的示例:

@GET
@Produces(MediaType.TEXT_PLAIN)
public void hello(@Suspended AsyncResponse response) throws InterruptedException {
response.resume(Response.ok().build());
Thread.sleep(10000);
System.out.println("Do some work");
}

最新更新