使用场景:
首页聚合接口
大屏聚合接口
发利息定时任务
使用姿势:
/**
* 核心线程 8 最大线程 20 保活时间30s 存储队列 10 有守护线程 拒绝策略:将超负荷任务回退到调用者
*/
private static ExecutorService executor = new ThreadPoolExecutor(8, 20,
30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(10),
new ThreadFactoryBuilder().setNameFormat("User_Async_FutureTask-%d").setDaemon(true).build(),
new ThreadPoolExecutor.CallerRunsPolicy());
public UserBehaviorDataDTO getUserAggregatedResult(final Long userId) {
long fansCount = 0, msgCount = 0, collectCount = 0,
followCount = 0, redBagCount = 0, couponCount = 0;
try {
Future<Long> fansCountFT = executor.submit(() -> userService.countFansCountByUserId(userId));
Future<Long> msgCountFT = executor.submit(() -> userService.countMsgCountByUserId(userId));
Future<Long> collectCountFT = executor.submit(() -> userService.countCollectCountByUserId(userId));
Future<Long> followCountFT = executor.submit(() -> userService.countFollowCountByUserId(userId));
Future<Long> redBagCountFT = executor.submit(() -> userService.countRedBagCountByUserId(userId));
Future<Long> couponCountFT = executor.submit(() -> userService.countCouponCountByUserId(userId));
fansCount = fansCountFT.get();
msgCount = msgCountFT.get();
collectCount = collectCountFT.get();
followCount = followCountFT.get();
redBagCount = redBagCountFT.get();
couponCount = couponCountFT.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
log.error(">>>>>>聚合查询用户聚合信息异常:" + e + "<<<<<<<<<");
}
return UserBehaviorDataDTO.builder()
.fansCount(fansCount)
.msgCount(msgCount)
.collectCount(collectCount)
.followCount(followCount)
.redBagCount(redBagCount)
.couponCount(couponCount)
.build();
}
static ExecutorService executor = Executors.newFixedThreadPool(2);
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("爸:小红你去买瓶酒!");
try {
System.out.println("小红出去买酒了,女孩子跑的比较慢,估计5s后才会回来...");
Thread.sleep(5000);
return "我买回来了!";
} catch (InterruptedException e) {
return "来世再见!";
}
}, executor);
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
throw new InterruptedException();
} catch (InterruptedException e) {
return "这是我托人带来的口信,我已经不在了。";
}
}, executor);
future2.thenAccept((e) -> {
System.out.println("小红说:" + e);
});
future1.thenAccept((e) -> {
System.out.println("小明说:" + e);
});
executor.shutdown();