Spring Boot springmvc REST API 设置请求超时时间 request timeout

先加一个配置。设置超时时间。

spring:  
  mvc:
    async:
      request-timeout: 20

接口的方法返回参数必须是Callable

@RestController
public class TestController {
    
    @GetMapping("/test")
    public Callable<String> test(){
        return () -> {
            Thread.currentThread().wait(1000);
            return "abcd";
        };
    }
    
}

但是这样的话一般请求超时了会抛异常。可以加一个全局捕获。

@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler({IllegalMonitorStateException.class})
    public String handleException(IllegalMonitorStateException e) {
        return "请求超时了";
    }
    
}
posted @ 2022-04-26 10:13  卡文地洗  阅读(5094)  评论(0)    收藏  举报