REST-Endpoint: Async execution without return value

走远了吗. 提交于 2020-12-26 08:32:08

问题


My problem might be very easy to solve, but I don't get it at the moment. In my Quarkus-App I have a REST-Endpoint which should call a method, don't wait for the result and immediately return a 202-HTTP-Statuscode.

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

I've read the Quarkus-Documentation about Vert.x and asynchronous processing. But the point there is: the processing is done asynchronously, but the client waits for the result. My clients don't need to wait, because there is no return value. It's something like the invocation of a batch-processing.

So I need something like a new Thread, but with all the Quarkus-Context.


回答1:


We've found a solution:

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



回答2:


You can use @Suspended AsyncResponse response in parameters and make the method return void Here's example of a similar method:

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


来源:https://stackoverflow.com/questions/62537998/rest-endpoint-async-execution-without-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!