1. 业务需求,获取各个模块的消息数量
2. 如果接口使用顺序执行,需要等待所有的消息数量查询完成后返回,耗时为各模块耗时的总和
如:
/**
* 消息提示
* 技术通告:通告未读数
* 系统公告:公告的未读数
* 在线反馈:反馈回复但未读数
* @param currentUser
* @return
*/
@MsgTranslate
@RequestMapping("/msg")
public Result promptMessage(@CurrentUser UserDto currentUser){
// 技术通告 未读数
Long unread1 = bulletinService.unread(currentUser);
// 系统公告未读数
Long unread2 = sysNoticeService.unread(currentUser);
// 在线反馈 未读数
Long unread3 = feedbackService.unread(currentUser);
Map<String, Long> map = new HashMap<>();
map.put(EnumConstant.MENU_SYS_NOTIC_CODE, unread2);
map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, unread1);
map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, unread3);
return Result.success(map);
}
3. 使用异步查询【CompletableFuture】,等待所有线程查询后返回结果,耗时为各模块中耗时最大的时间
如:
/**
* 核心线程 8 最大线程 20 保活时间30s 存储队列 10 有守护线程 拒绝策略:将超负荷任务回退到调用者
*/
private static ExecutorService executor = new ThreadPoolExecutor(20, 50, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
/**
* 消息提示
* 技术通告:通告未读数
* 系统公告:公告的未读数
* 在线反馈:反馈回复但未读数
* @param currentUser
* @return
*/
@MsgTranslate
@RequestMapping("/msg")
public Result promptMessage(@CurrentUser UserDto currentUser){
// 技术通告 未读数
CompletableFuture<Long> bulletinFT = CompletableFuture.supplyAsync(() -> bulletinService.unread(currentUser), executor);
// 系统公告 未读数
CompletableFuture<Long> noticeFT = CompletableFuture.supplyAsync(() -> sysNoticeService.unread(currentUser), executor);
// 在线反馈 未读数
CompletableFuture<Long> feedbackFT = CompletableFuture.supplyAsync(() -> feedbackService.unread(currentUser), executor);
Map<String, Long> map = new HashMap<>();
try {
// 聚合所有的查询 等所有的查询都查询完 最多等10秒
CompletableFuture.allOf(bulletinFT, noticeFT, feedbackFT).get(10, TimeUnit.SECONDS);
map.put(EnumConstant.MENU_SYS_NOTIC_CODE, noticeFT.get());
map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, bulletinFT.get());
map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, feedbackFT.get());
} catch (Exception e) {
map.put(EnumConstant.MENU_SYS_NOTIC_CODE, 0);
map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, 0);
map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, 0);
}
return Result.success(map);
}