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 "后端业务逻辑正在处理,请耐心等待"; } } } }
标签:springboot,springframework,annotation,util,API,org,import,超时,public 来源: https://www.cnblogs.com/yuarvin/p/16525932.html