Java分布式异步控制

1-controller层

    // 这个里面放置的都是异步的类 每个使用IAsyncBssService,都需要添加Lazy,不加有可能会出现循环依赖
    @Autowired
    @Lazy
    IAsyncBssService iAsyncBssService;

    public IResponse<Void> dataAsyncList(@RequestBody(required = false) String code){
        for (int i = 0; i < 5; i++) {
            iAsyncBssService.dloanEntConditionJobAsyn(i, null);
        }
        return null;
    }

2-service层

    // Async中的value可以自定义核心线程数,存活时间,队列长度等
    // asyn_wait_time=4  asyn_release_time=2
    @Override
    @Async
    public void dloanEntConditionJobAsyn(Integer pageIndex, List<DloanDto> dloanDtoList) {
        logger.info("等待异步--{}--开始time:{}", pageIndex, DateUtils.getCurrentDateTime());
        try {
            RedisUtils.lockTemplate(asyn_prefix, asyn_wait_time, asyn_release_time, TimeUnit.MINUTES).execute(()->{
                logger.info("进入异步--{}--开始time:{}", pageIndex, DateUtils.getCurrentDateTime());
                // 执行1分钟
                Thread.sleep(1000 * 60 * 1);
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        logger.info("结束异步--{}--开始time:{}", pageIndex, DateUtils.getCurrentDateTime());
    }

3-执行结果

// 外层controller循环5次进来
等待异步--0--开始time:2023-08-03T10:25:22.464
等待异步--2--开始time:2023-08-03T10:25:22.464
等待异步--1--开始time:2023-08-03T10:25:22.464
等待异步--3--开始time:2023-08-03T10:25:22.464
等待异步--4--开始time:2023-08-03T10:25:22.464

// 一起进来后,开始争夺线程使用权
进入异步--2--开始time:2023-08-03T10:25:22.610
结束异步--2--开始time:2023-08-03T10:26:22.665

进入异步--4--开始time:2023-08-03T10:26:22.692
结束异步--4--开始time:2023-08-03T10:27:22.834

进入异步--3--开始time:2023-08-03T10:27:22.847
结束异步--3--开始time:2023-08-03T10:28:22.873

进入异步--1--开始time:2023-08-03T10:28:22.894
结束异步--1--开始time:2023-08-03T10:29:22.938

// 这里缺少了【等待异步0】的执行,因为一起进来的时候,设置的等待时间是4,又因为执行方法里面每个进来执行1分钟,导致最后这个【等待异步0】等待超时
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容