springboot中设置API代码的超时时间
因为web服务本身的持久性,大多数时候超时设置应该在请求方设置;
当前一个springboot框架的web项目有一个需求,需要给api设置最大响应时间,超过这个时间,服务自动返回默认值给请求方。
现在有如下操作:
一、主线启动类加异步支持注解
package com.zving; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class WebApplication { public static void main(String[] args) { SpringApplication.run(WebApplication.class, args); } }
二、主要的逻辑代码独立出来,放入另一个文件中,接口api异步调用该逻辑代码
package com.zving.util; import java.util.concurrent.Future; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; @Component public class ApiUtil { @Async public Future<String> submitFun() throws InterruptedException { //业务逻辑具体代码 Thread.sleep(4000); return new AsyncResult<String>("后端业务逻辑已经处理完成"); } }
三、接口的线程有时间比较,超过时间则返回一个默认值
package com.zving.controller; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.annotation.Resource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.zving.util.ApiUtil; @RestController public class ApiController { @Resource private ApiUtil util; @GetMapping(value = "/submit") public String submit() throws InterruptedException, ExecutionException { long oldTime = System.currentTimeMillis(); Future<String> result = util.submitFun(); while(true) { long newTime = System.currentTimeMillis(); if(result.isDone()) { return result.get(); } if(newTime-oldTime>3000) { return "后端业务逻辑正在处理,请耐心等待"; } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?