简体   繁体   English

REST-Endpoint:没有返回值的异步执行

[英]REST-Endpoint: Async execution without return value

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.在我的 Quarkus 应用程序中,我有一个 REST 端点,它应该调用一个方法,不要等待结果并立即返回 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.我已阅读有关 Vert.x 和异步处理的 Quarkus 文档。 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.所以我需要一个new Thread之类的东西,但要包含所有 Quarkus-Context。

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

You can use @Suspended AsyncResponse response in parameters and make the method return void Here's example of a similar method:您可以在参数中使用@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");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM