Spring Boot REST API - 请求超时?

新手上路,请多包涵

我有一个 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();
}

没有任何运气。

我怀疑我必须手动计时所有第三方调用,如果它们花费的时间太长,则抛出超时异常。那正确吗?或者是否有任何更简单、更全面的解决方案涵盖我的所有请求端点?

原文由 Jesper N 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

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

 @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";
        }
    };
}

原文由 Cyril 发布,翻译遵循 CC BY-SA 4.0 许可协议

@Transactional 注释采用超时参数,您可以在其中为 @RestController 中的特定方法指定超时(以秒为单位)

 @RequestMapping(value = "/method",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)

原文由 fvorraa 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题