IT-迁哥
发布于 2024-01-29 / 140 阅读
41
0

springboot异步执行工具

springboot异步执行工具类,在首页,多详情等的前端页面上,经常是由非常多的接口组成的,这个时候我们又不想前端发那么多请求,就会把多个接口的内容聚合到一个接口里面,工具应运而生。

实现原理是利用springboot的异步执行原理,要先用@EnableAsync打开异步支持,需要的话可以自己再配置线程池。

1.SpringAsyncTaskUtil工具类


/**
 * @Author glq
 */
@Component
public class SpringAsyncTaskUtil {
    /**
     * 执行耗时是否开启
     */
    private final boolean execTimes = true;

    /**
     * 公共异步任务,返回值模型
     */

    @Async
    public <T> Future<T> commonAsyncTask(Callable<T> callable) throws Exception {
        long start = System.currentTimeMillis();
        T call = callable.call();
        if(execTimes){
            System.err.println(Thread.currentThread().getName()+"执行时长:"+(System.currentTimeMillis()-start)+"ms");
        }
        return new AsyncResult<>(call);
    }

    public String test(String str){

        return str;
    }

}


评论