本文介绍了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:@Overridepublic void configureAsyncSupport(final AsyncSupportConfigurer configurer) { configurer.setDefaultTimeout(5000); configurer.registerCallableInterceptors(timeoutInterceptor());}@Beanpublic 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?推荐答案如果你想要 spring.mvc.async.request-timeout=5000 你需要返回一个 Callable 开始工作.You need to return a Callable<> 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