泽西AsyncResponse和响应

时间:2018-01-25 06:34:45

标签: jersey jax-rs

我想使用AsyncResponse返回一个temporaryRedirect。

以下“工作”(因为没有错误),但似乎不是异步的(它一次处理一个请求)。

    @GET
    public Response doLoad(@Suspended final AsyncResponse asyncResponse,
            @QueryParam("path") String path)  {

        Response response = veryExpensiveOperation(path);
        asyncResponse.resume(response);
        return response;
    }

    private Response veryExpensiveOperation(String path)  {
        // veryExpensiveOperation
    }

这应该有用吗?如果我明确需要在https://jersey.github.io/documentation/latest/async.html#d0e9895开始一个新的线程,那么返回响应的样子是什么?

1 个答案:

答案 0 :(得分:2)

我认为您没有正确使用异步上下文。从我看到的,你是阻止请求处理线程。你不应该在vertx中阻止这个线程。如何做如下:

    @GET
    public void doLoad(@Suspended final AsyncResponse asyncResponse,
            @QueryParam("path") String path)  {

        CompletableFuture<Response> future = veryExpensiveOperation(path);
        future.thenAccept(resp -> asyncResponse.resume(resp));
    }    

    private CompletableFuture<Response> veryExpensiveOperation(String path){
        CompletableFuture<Response> completableFuture = new CompletableFuture<>();

        new Thread(() -> {
            //do expensive stuff here
            completableFuture.complete(Response.ok().entity("Completed").build());
        }).start();

        return completableFuture;
    }