项目使用jdk1.8CompletableFuture异步 来进行需求使用推送消息
优点:实现了Future和CompletionStage接口,保留了Future的优点,并且弥补了其不足。即异步的任务完成后,需要用其结果继续操作时,无需等待。
/ try {
//异步获取用户名称
CompletableFuture<String> applyNickName = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
String applyNickName = "";
applyNickName = nodeService.getNickName(order.getApplyUserId());
return applyNickName;
}
});
//处理该异步结果
CompletableFuture<Void> categoryView = applyNickName.thenAcceptAsync(new Consumer<String>() {
@Override
public void accept(String itemInfo) {
List<SingleAppPushReq> reqList = new ArrayList<>();
List<UserMsgVO> userRoleMsgVOList = new ArrayList<>();
List<UserMsgVO> userMsgVOList = new ArrayList<>();
List<Integer> userIdList = new ArrayList<>();
for (ApplyOrderTask task : taskList) {
if (task.getVerifyType().intValue() == NodeVerifyTypeConstant.ROLE_TASK) {
//角色类型的消息推送
userRoleMsgVOList = userService.getUserMsgVOListByRoleId(task.getVerifyRoleId(), SecurityConstants.FROM_IN);
} else {
//用户类型推送
userIdList.add(task.getVerifyUserId());
}
}
if (!userIdList.isEmpty()) {
userMsgVOList = userService.getUserMsgVOListByIds(userIdList, SecurityConstants.FROM_IN);
}
userMsgVOList.addAll(userRoleMsgVOList);
if (null == userMsgVOList || userMsgVOList.isEmpty()) {
log.warn("当前用车任务找不到推送人", event);
return;
}
for (UserMsgVO userMsgVO : userMsgVOList) {
SingleAppPushReq req = new SingleAppPushReq();
req.setMsgType(MsgTypeConstant.VEHICEL_NOTIFICATION);
req.setAppCarId(order.getOrderId());
req.setUserId(userMsgVO.getUserId());
req.setTitle(template.getTitle());
req.setContent(MessageFormat.format(template.getContent(), userMsgVO.getNickName()));
if (order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_VERIFY
|| order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_RECIVE
|| order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_DISTRIBUTION) {
if (order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_VERIFY) {
req.setContent(itemInfo + "提交的用车申请需要您审批,请及时处理");
}
if (order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_RECIVE) {
req.setContent(itemInfo + "提交的还车申请需要您审批,请及时处理");
}
if (order.getProcessStatus().intValue() == ProcessStatusConstant.WAIT_DISTRIBUTION) {
req.setContent(itemInfo + "提交的用车申请需要您派车,请及时处理");
}
// req.setContent(MessageFormat.format(template.getContent(), applyNickName));
} else {
req.setContent(MessageFormat.format(template.getContent(), userMsgVO.getNickName()));
}
reqList.add(req);
}
if (reqList.isEmpty()) {
return;
}
try {
msgAppPushFeign.batchAppSinglePush(reqList, SecurityConstants.FROM_IN);
} catch (Exception e) {
log.error("调取消息服务推送消息失败", e);
}
}
});
//返回实例
CompletableFuture.allOf(applyNickName,categoryView).join();
异步其实是为了压榨CPU的各种核心,让它们同时去工作。所以一旦以异步的情况下,这个吞吐量就会大量提高