5

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.

Simon Wick
  • 249
  • 1
  • 11

2 Answers2

5

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();
}
Simon Wick
  • 249
  • 1
  • 11
  • Just for completeness: There are some problems with `@RequestScope` when using this async approach: https://github.com/quarkusio/quarkus/issues/13013 – Simon Wick Dec 07 '20 at 15:01
0

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");
    }
Dmytro Chaban
  • 1,106
  • 1
  • 11
  • 19
  • Thanks for your answer. I added a comment at @Kavithakaran 's answer. It works, but I'm having problem with the context. – Simon Wick Jun 24 '20 at 04:49