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

SpringBoot如何实现接口超过3秒未返回响应时自动触发超时

配置不生效的原因

server.servlet.session.timeout 是会话超时配置,作用是控制用户会话(Session)的有效期,和单次接口请求的处理超时没有关联,因此无法实现你的需求。

实现方案

方案1:全局异步请求超时配置(官方推荐)

Spring Boot 内置了异步请求的超时控制,是实现接口超时最稳妥的方式,步骤如下:

  1. 启动类添加 @EnableAsync 注解开启异步功能:
@SpringBootApplication
@EnableAsync
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}
  1. 在 application.properties 中添加超时配置,单位为毫秒:
# 配置异步请求处理超时为3秒
spring.mvc.async.request-timeout=3000
  1. 改造接口返回异步结果:
@GetMapping("/api")
public CompletableFuture<Data> getData(){
    return CompletableFuture.supplyAsync(() -> {
        try {
            // 替换为实际业务逻辑
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException("业务中断", e);
        }
        return new Data();
    });
}

超时后会自动抛出超时异常,你可以通过全局异常处理器统一封装返回格式。

方案2:单个接口独立超时控制

如果只需要给特定接口配置超时,不需要全局生效,可以借助Guava的时间限制工具实现:

  1. 引入Guava依赖(Maven为例):
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>32.1.3-jre</version>
</dependency>
  1. 接口代码改造:
@GetMapping("/api")
public Data getData() throws Exception {
    TimeLimiter timeLimiter = SimpleTimeLimiter.create(Executors.newCachedThreadPool());
    // 指定业务逻辑执行超时时间为3秒
    return timeLimiter.callWithTimeout(() -> {
        Thread.sleep(10000);
        return new Data();
    }, 3, TimeUnit.SECONDS);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:36:02