资讯详情

springboot接口超时配置

1.配置

提示:springboot项目设置界面超时(基本配置)

//单位是毫秒哦 2000代表2秒

spring:

mvc:

async:

request-timeout: 2000

配置不好用配置不好用 继续往下看

提示:要使配置生效,必须符合本配置对应的接口规范.

2.接口定义

提示:首先是异步,需要单独打开一个线程来执行.第二个返回值是Callable<泛型>,泛型是你真正想要返回的数据类型.

package com.elco.datamp.controller;  import com.elco.core.entity.ResponseResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;  import java.util.concurrent.Callable;   @RestController @RequestMapping ("/ApiTimeOut") @Api (value = "测试接口超时", tags = {"测试接口超时"}) public class TimeOutMethod {      /**      * 设置超时测试接口.通常如下      *      * @return 返回值必须是Callable<T>的.      */     @PostMapping (value = "/test")     @ApiOperation ("测试超时")     public Callable<ResponseResult<String>> timeOutMethod() {         //new Callable<> 单独打开一个线程执行         return new Callable<ResponseResult<String>>(){             @Override             public ResponseResult<String> call() throws Exception {                 ///这里会触发超时                 Thread.sleep(10000);                 //正常返回逻辑                 ResponseResult<String> responseResult = new ResponseResult<String>();                 responseResult.setMsg("返回超时");                 return responseResult;             }         };     }  }

3.异常处理

提示:捕获AsyncRequestTimeoutException异常,统一处理.

package com.elco.datamp.utils;  import cn.hutool.core.date.DateTime; import com.alibaba.fastjson.JSONObject; import com.elco.core.entity.ResponseResult; import com.elco.core.exception.BusinessException; import com.elco.datamp.enums.UserErrorEnum; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.async.AsyncRequestTimeoutException;  @ControllerAdvice //所有的Controller都会进入这一类? public class BaseExceptionAdvice {     @ExceptionHandler ( AsyncRequestTimeoutException.class)     public ResponseEntity<JSONObject> handException(AsyncRequestTimeoutException e) {         JSONObject jsonObject = new JSONObject();         jsonObject.put("timestamp", DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));         jsonObject.put("code", "150010");         jsonObject.put("msg","下载超时");         jsonObject.put("data",null);         return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonObject);     }  }

标签: elco光电传感器op18

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

 锐单商城 - 一站式电子元器件采购平台  

 深圳锐单电子有限公司