美文网首页
Java分布式异步控制

Java分布式异步控制

作者: CoderLJW | 来源:发表于2023-08-02 10:42 被阅读0次

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】等待超时

相关文章

网友评论

      本文标题:Java分布式异步控制

      本文链接:https://www.haomeiwen.com/subject/avtppdtx.html