请求超时处理

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
public class TimeOutUtil {

    private static int ms;
	//静态变量读取配置文件,@component
    @Value("${myTimeOut.ms}")
    private void setMs(int ms) {
        TimeOutUtil.ms = ms;
    }

    /**
     * 用于执行任务的线程池
     */
    private static ExecutorService executorService = new ThreadPoolExecutor(10, 10, 30L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));

    /**
     * 执行任务,而且超时时间为800毫秒
     *
     * @param callable 须要执行的任务
     * @param <T>      任务执行完毕后返回值类型
     * @return 任务结果
     */
    public static <T> T execute(Callable<T> callable) {

        // 提交任务
        Future<T> future = executorService.submit(callable);

        try {
            return future.get(TimeOutUtil.ms, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }
}

//调用
TimeOutUtil.execute(() -> 执行方法)

posted @ 2022-07-08 11:18  Leejk  阅读(45)  评论(0编辑  收藏  举报