如何让Java rest api调用立即返回不等?

时间:2016-12-01 09:02:43

标签: java spring asynchronous

@RequestMapping(value = "/endpoint", method = RequestMethod.POST)
    public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) {
        somefunction();
        return new ResponseEntity<>(HttpStatus.OK);
    }


public somefunction() {
 .....
 }

在Java spring controller中,我有一个端点。调用此端点时,我希望它直接返回,而不是等待somefunction()完成。任何人都可以教我如何处理这个问题?

3 个答案:

答案 0 :(得分:6)

如果您使用的是Java 8,则可以使用新的Executor类:

@RequestMapping(value = "/endpoint", method = RequestMethod.POST)
public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) {
    Executors.newScheduledThreadPool(1).schedule(
        () -> somefunction(),
        10, TimeUnit.SECONDS
    );
    return new ResponseEntity<>(HttpStatus.ACCEPTED);
}

这将:

  1. 安排somefunction()在延迟10秒后运行。
  2. 返回HTTP 202已接受(当您的POST端点实际上没有在现场创建任何内容时,应该返回此内容。)
  3. 10秒后运行somefunction()

答案 1 :(得分:2)

更改行

if (e.keyCode == 37) { //move left or wrap
        temp = active;
        while (temp > 0) {
            temp = temp - 1;
            // only advance if there is an input field in the td
            if ($('.tblnavigate tbody tr td').eq(temp).find('input:not(:disabled)').length != 0) {
                active = temp;
                break;
            }
        }
    }

somefunction();

答案 2 :(得分:1)

您应该使用RxJava为您提供承诺。您将DefferedResult异步返回,因此不会阻止其他方法被执行。

例如:

@RequestMapping("/getAMessageFutureAsync")
public DeferredResult<Message> getAMessageFutureAsync() {
    DeferredResult<Message> deffered = new DeferredResult<>(90000);
    CompletableFuture<Message> f = this.service1.getAMessageFuture();
    f.whenComplete((res, ex) -> {
        if (ex != null) {
            deffered.setErrorResult(ex);
        } else {
            deffered.setResult(res);
        }
    });
    return deffered;
}

--Code source and tutorial