场景:项目分配权限的场景,想着可能当用户点击了某一组织权限,需要将这个组织的权限和这个组织下的人的存放到权限表,如果操作等太久,就想到了异步处理,了解到Java8有CompletableFuture这个类来实现,在其中遇到了,注入的Service和Mapper的NPE问题,一直很纳闷,最后了解到,线程为了安全起见,防止注入的操作,(这里参考了https://www.cnblogs.com/xiaolong1996/p/9571645.html这个博客得以解决)
以下是CompletableFuture实现的代码
public class Main {
public static Boolean dispatchPermission() {
try {
Thread.sleep(60000);
System.out.println("正在分配权限 ");
} catch (InterruptedException e) {
}
if (Math.random() < 0.3) {
throw new RuntimeException("分配权限失败");
}
return true;
}
public static void async() {
ExecutorService executor = Executors.newFixedThreadPool(4);
// 创建异步执行任务:
CompletableFuture<Boolean> cf = CompletableFuture.supplyAsync(() -> {
Boolean flagBoolean= dispatchPermission();
return true;
}, executor);
// 执行成功:
cf.thenAccept((result) -> {
System.out.println("reulst: " + result);
});
// 异常:
cf.exceptionally((e) -> {
System.out.println("exception: " + e.getMessage());
e.printStackTrace();
return null;
});
}
public static void main(String[] args) throws InterruptedException {
Thread.sleep(100);
async();
System.out.println("已完成权限分配");
}
}