You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot REST接口超时配置:全局默认与特定端点自定义

Spring全局与特定异步端点超时配置方案

首先明确两个核心超时概念,别搞混:

  • HTTP客户端读取超时:你用SimpleClientHttpRequestFactory设置的readTimeout,是RestTemplate发起外部HTTP请求时的读取超时,和控制器的异步端点超时完全无关。
  • 异步请求超时:application.yml里的spring.mvc.async.request-timeout,才是控制@Async标注的控制器方法、容器等待异步任务完成的超时时间,这正是你要调整的目标。

一、全局默认异步超时(60秒)

直接在application.yml里配置全局规则:

spring:
  mvc:
    async:
      request-timeout: 60000 # 单位毫秒,对应60秒

这个配置会自动应用到所有没指定自定义执行器的@Async控制器方法上。

二、为特定@Async端点设置120秒超时

@Async注解本身没法直接指定超时,得靠自定义异步任务执行器来实现:

1. 配置自定义异步执行器

创建一个配置类,定义两个执行器:一个默认60秒,一个120秒的:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;

@Configuration
@EnableAsync // 必须加这个注解开启异步支持
public class AsyncConfig {

    // 默认异步执行器,60秒超时
    @Bean("defaultAsyncExecutor")
    public Executor defaultAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("DefaultAsync-");
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    // 120秒超时的自定义执行器
    @Bean("longTimeoutAsyncExecutor")
    public Executor longTimeoutAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("LongTimeoutAsync-");
        executor.setAwaitTerminationSeconds(120);
        executor.initialize();
        return executor;
    }
}

2. 在目标端点绑定自定义执行器

修改你的addContractStudents方法,在@Async注解里指定用120秒的执行器:

@Async("longTimeoutAsyncExecutor")
@RequestMapping(value = Array("/{id}/students"), method = Array(RequestMethod.POST))
def addContractStudents(
...

补充提醒

  • 启动类必须加上@EnableAsync注解,不然异步配置不会生效。
  • 你之前配置的SimpleClientHttpRequestFactory是管RestTemplate调用外部接口的超时,和控制器的异步端点超时是两条线,各自独立生效。

内容的提问来源于stack exchange,提问作者sming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 04:15:47