springboot接口自定义超时时间

  1. application.prop
#超时时间
timeout.maxMills= 5000
#自定义超时时间
timeout.map={'createVerifyInI.do':'1000', 'createVerifyBI.do':'5000', 'createVerifyByMappingInI.do':'1'}

  1. 切面
import com.alibaba.fastjson.JSON;
import com.neo.vo.response.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Component
@Aspect
public class ResponseTimeAspect {
    @Value("${timeout.maxMills:5000}")
    private int time;
    @Value("#{${timeout.map}}")
    private Map<String,String> map;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Around("@annotation(postMapping)")
    public Object around(ProceedingJoinPoint joinPoint, RequestMapping postMapping) {
        final Future<Object> future = threadPoolTaskExecutor.submit(() -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable throwable) {
                throw new RuntimeException(throwable);
            }
        });
        try {
            HttpServletRequest request =
                    ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
            final String uri = request.getRequestURI();
            for (Map.Entry<String,String> entry  :map.entrySet()) {
                if(uri.endsWith(entry.getKey())){
                    // 获取响应,超过配置毫秒抛出超时异常
                    return future.get(Integer.valueOf(entry.getValue()), TimeUnit.MILLISECONDS);
                }
            }
            return future.get(time, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            return "被中断了";
        } catch (ExecutionException e) {
            return "执行任务发生异常";
        } catch (TimeoutException e) {
            ResponseResult responseResult = new ResponseResult();
            responseResult.setStatFlag(1);
            responseResult.setMessage("接口超时");
            return responseResult;
        }
    }

}

你可能感兴趣的:(spring,boot,后端,java)