本文介绍了Spring Boot REST API - 请求超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring Boot REST服务,有时会将第三方服务作为请求的一部分。我想在我的所有资源上设置一个超时(让我们说5秒),这样如果任何请求处理(整个链,从传入到响应)花费的时间超过5秒,我的控制器会响应HTTP 503而不是实际响应。如果这只是一个Spring属性会很棒,例如设置

I have a Spring Boot REST service that sometimes call third party services as a part of a request. I would like to set a timeout on all my resources (let's say 5 seconds), so that if any request handling (the whole chain, from incoming to response) takes longer than 5 seconds my controllers responds with HTTP 503 instead of the actual response. It would be awesome if this was just a Spring property, for example setting

spring.mvc.async.request-timeout=5000

但我没有运气。我还尝试扩展WebMvcConfigurationSupport并覆盖configureAsyncSupport:

but I haven't had any luck with that. I've also tried extending WebMvcConfigurationSupport and overriding configureAsyncSupport:

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

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

没有任何运气。

我怀疑我必须手动计算所有第三方呼叫的时间,如果花费的时间太长,则抛出超时异常。是对的吗?或者是否有更简单的整体解决方案覆盖我的所有请求端点?

I suspect I have to manually time all my third party calls, and if they take too long, throw a timeout exception. Is that right? Or is there any easier, holistic solution that covers all my request endpoints?

推荐答案

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

You need to return a Callabe if you want spring.mvc.async.request-timeout=5000 to work.

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

这篇关于Spring Boot REST API - 请求超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:50