如何在Spring Boot REST API上设置超时?

Tom*_*hir 8 java rest timeout spring-boot

我有一些REST API可能需要一段时间才能执行,并且我想限制其执行时间。最好是,如果经过30秒并且请求没有返回,我想返回特定的HTTP代码/数据并完全终止该请求。

当前代码:

@RestController
@CrossOrigin(origins = {"*"}, maxAge = 4800, allowCredentials = "false")
public class APIController {

@RequestMapping(value = "/api/myapifunc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> optimize(@RequestParam(value="param1", defaultValue="")) {
    // Code here
}
Run Code Online (Sandbox Code Playgroud)

小智 0

@RequestMapping(value = "/api/myapifunc", method = RequestMethod.POST, produces = 
"application/json")
public ResponseEntity<?> optimize(@RequestParam(value="param1", defaultValue="")) {
 return new Callable<String>() {
    @Override
    public String call() throws Exception {
        Thread.sleep(3000); //this will cause a timeout
        return "foobar";
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

未来你可以使用或者注释 @Timed @Transactional(timeout = 3000)