1-controller層
// 這個(gè)里面放置的都是異步的類 每個(gè)使用IAsyncBssService,都需要添加Lazy,不加有可能會(huì)出現(xiàn)循環(huán)依賴
@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可以自定義核心線程數(shù),存活時(shí)間,隊(duì)列長(zhǎng)度等
// 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("進(jìn)入異步--{}--開始time:{}", pageIndex, DateUtils.getCurrentDateTime());
// 執(zhí)行1分鐘
Thread.sleep(1000 * 60 * 1);
});
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
logger.info("結(jié)束異步--{}--開始time:{}", pageIndex, DateUtils.getCurrentDateTime());
}
3-執(zhí)行結(jié)果
// 外層controller循環(huán)5次進(jìn)來
等待異步--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
// 一起進(jìn)來后,開始爭(zhēng)奪線程使用權(quán)
進(jìn)入異步--2--開始time:2023-08-03T10:25:22.610
結(jié)束異步--2--開始time:2023-08-03T10:26:22.665
進(jìn)入異步--4--開始time:2023-08-03T10:26:22.692
結(jié)束異步--4--開始time:2023-08-03T10:27:22.834
進(jìn)入異步--3--開始time:2023-08-03T10:27:22.847
結(jié)束異步--3--開始time:2023-08-03T10:28:22.873
進(jìn)入異步--1--開始time:2023-08-03T10:28:22.894
結(jié)束異步--1--開始time:2023-08-03T10:29:22.938
// 這里缺少了【等待異步0】的執(zhí)行,因?yàn)橐黄疬M(jìn)來的時(shí)候,設(shè)置的等待時(shí)間是4,又因?yàn)閳?zhí)行方法里面每個(gè)進(jìn)來執(zhí)行1分鐘,導(dǎo)致最后這個(gè)【等待異步0】等待超時(shí)