小编典典

Spring Boot REST API-请求超时?

spring

我有一个Spring Boot REST服务,有时会在请求中调用第三方服务。我想对所有资源设置一个超时时间(假设为5秒),这样,如果任何请求处理(从输入到响应的整个链)花费的时间超过5秒,我的控制器将使用HTTP 503而不是实际响应进行响应。如果这只是一个Spring属性,那就太好了,例如设置

spring.mvc.async.request-timeout=5000

但是我没有任何运气。我也尝试过扩展WebMvcConfigurationSupport并覆盖configureAsyncSupport:

@Override
public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
    configurer.setDefaultTimeout(5000);
    configurer.registerCallableInterceptors(timeoutInterceptor());
}

@Bean
public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
    return new TimeoutCallableProcessingInterceptor();
}

没有任何运气。

我怀疑我必须手动为所有第三方呼叫计时,如果它们花费的时间太长,则会抛出超时异常。那正确吗?还是有一个更简单,整体的解决方案可以覆盖我的所有请求端点?


阅读 661

收藏
2020-04-12

共1个答案

小编典典

Callable<>如果你想spring.mvc.async.request-timeout=5000工作,则需要返回a 。

@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(8000); //this will cause a timeout
            return "foobar";
        }
    };
}
2020-04-12