Java Future 对象在 onComplete 之后从 API 返回值

问题描述 投票:0回答:1

我有一个如下所示的 API 方法,该方法返回

ResponseEntity<JsonNode>
。我不知道如何等待它并在 Future
onComplete
方法中返回值。

public ResponseEntity<JsonNode> doSomeAction(
        @ApiParam(name = "mode", required = true) @PathVariable final String mode,
        @RequestBody SomeAction action, HttpServletRequest request) throws IOException) {

            if(mode.equals("POWER"){
                Future<JsonObject> future = someAppService.generatePower(action);
                future.onComplete( result -> {
                    return new ResponseEntity<JsonNode>(JsonHelper.toJsonNode(result.result().encode()), HttpStatus.OK)
                    //above return is not valid but i want to return here as soon as future completes

                });
            }
            if(mode.equals("someOtherMode"){

                //some code here

            }
            return new ResponseEntity<JsonNode>(JsonHelper.getObjectMapper().valueToTree(someResponse), headers, HttpStatus.OK);
}

基本上,我想在

onComplete
方法中返回值,即在执行generatePower()方法之后,该方法在内部调用一些API,这可能需要一些时间。 我尝试使用
DeferredResult<JsonNode>
但它不起作用。有什么想法吗?

java completable-future
1个回答
0
投票

您可以使用 CountDownLatch 来等待结果:

    public ResponseEntity<JsonNode> doSomeAction(
            @ApiParam(name = "mode", required = true) @PathVariable final String mode,
            @RequestBody SomeAction action, HttpServletRequest request) throws IOException) {

                ResponseEntity<JSonObbject> result = null;
                CountDownLatch ready = new CountDownLatch(1);
                if(mode.equals("POWER"){
                    Future<JsonObject> future = someAppService.generatePower(action);
                    future.onComplete( result -> {
                        result = new ResponseEntity<JsonNode>(JsonHelper.toJsonNode(result.result().encode()), HttpStatus.OK)
                        ready.countDown();
                    });
                }
                if(mode.equals("someOtherMode"){
    
                    //code that updates result variable
    
                }
                
                if (!ready.await(timeout, SECONDS) {
                    // return error or throw appropriate exception
                }
                return result;
    }
© www.soinside.com 2019 - 2024. All rights reserved.