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);
    }

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐