@Async

场景:使用线程池异步插入数据,等所有插入完成后返回执行成功信息。

用了@Async方法之后,发现主线程已经返回给前端了,说我已经把数据都插完了,但实际上还有其他子线程在背后偷偷摸摸插数据。。。这个有点过分吧?
在这里插入图片描述
在网上查找了许多方法,都不太合我胃口。。。
在这里插入图片描述
其中这篇给我的灵感挺多的:https://www.cnblogs.com/lixin-link/p/10998058.html
感谢!!
在这里插入图片描述
主要还是靠用Future来解决问题的

List<Future> futureList = new ArrayList<>();
        for (List<Pojo> list : lists) {
            //下面这个方法在方法上使用了@Async注解的
            Future future = service.insertBatch(list);
            futureList.add(future);
        }
        while (true) {
            if (null != futureList) {
                boolean isAllDone = true;
                for (Future future : futureList) {
                    if (null == future || !future.isDone()) {
                        isAllDone = false;
                    }
                }
                if (isAllDone) {
                    break;
                }
            }
        }

insertBatch方法大致代码如下(〃'▽'〃)

 @Async
    public Future insertBatch(List<Pojo> list) {

        if (!CollectionUtils.isEmpty(list)) {
            pojoMapper.insertBatch(list);   
        }
        //返回需要用AsyncResult类,我也没试过其他的
        return new AsyncResult(null);
    }

最后我得到了~
在这里插入图片描述
在这里插入图片描述
没辍!这就是我要的~٩(๑>◡<๑)۶

告辞!

1

2

3

 

https://blog.csdn.net/fwk19840301/article/details/90082867?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-14&spm=1001.2101.3001.4242

springboot+async异步接口实现和调用(同类里面方法调用不生效解决)

https://www.cnblogs.com/ssslinppp/p/7940565.html

http://wanhejia.com/qianduan/213.html

posted @ 2020-11-03 17:32  edda_huang  阅读(107)  评论(0编辑  收藏  举报