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

c23*_*878 5 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() {
 .....
 }
Run Code Online (Sandbox Code Playgroud)

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

wal*_*len 7

如果您使用的是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);
}
Run Code Online (Sandbox Code Playgroud)

这将:

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


Chi*_*hiu 4

换线

somefunction();
Run Code Online (Sandbox Code Playgroud)

成为

new Thread()
{
    public void run() {
        somefunction();
    }
}.start();
Run Code Online (Sandbox Code Playgroud)