电商项目——全文检索-ElasticSearch——第一章——中篇
电商项目——商城业务-商品上架——第二章——中篇
电商项目——商城业务-首页——第三章——中篇
电商项目——性能压测——第四章——中篇
电商项目——缓存——第五章——中篇
电商项目——商城业务-检索服务——第六章——中篇
电商项目——商城业务-异步——第七章——中篇
电商项目——商品详情——第八章——中篇
电商项目——认证服务——第九章——中篇
电商项目——购物车——第十章——中篇
电商项目——消息队列——第十一章——中篇
电商项目——订单服务——第十二章——中篇
电商项目——分布式事务——第十三章——中篇
文章目录
1:异步复习
2:线程池详解
3:CompletableFuture
- 在分布式架构中,我们还有一个需要解决的复杂任务场景,比如A,B,C三个异步任务进行运行,C必须等待A运行完的返回结果后才可以运行,B又不用等A,C我们可以直接异步运行,我们要编排好他们的业务进行异步调用又是一个复杂的过程,我们举一个例子,如下就是在分布式架构中搭建电商项目遇到的一个问题
我们必须要先完成1以后,查询完sku,才知道它对应的spu,知道了spu以后,我们才可以完成4,5,6(4,5,6可以并发执行),我们这就要使用CompletableFuture异步编排来解决
我们就可以使用CompletableFuture来解决这个问题
3.1 启动异步任务
代码测试
//我们自己创建的一个线程池
public static ExecutorService executor= Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main。。。。start..");
CompletableFuture.runAsync(()->{
System.out.println("当前线程:"+Thread.currentThread().getId());
int i=10/2;
System.out.println("运行结果:"+i);
},executor);
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}, executor);
System.out.println("supplyAsync运行的结果:"+future.get());
System.out.println("main。。。。end..");
}
3.2 完成回调与异常感知
代码测试:下面的代码测试涉及到java8新特性函数式接口
Java8新特性——核心——Lambda和Stream
Java8 引入了函数式接口,并在java.util.function 包内预定义了常用函数式接口,下表罗列了一些常用的函数式接口:
//我们自己创建的一个线程池
public static ExecutorService executor= Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main。。。。start..");
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
System.out.println("当前线程:" + Thread.currentThread().getId());
/**
* @FunctionalInterface
public interface Supplier<T> {
* @return a result
T get();
}
*/
int i = 10 / 0;
System.out.println("运行结果:" + i);
return i;
}, executor).whenComplete((res,exc)->{
/**
* @FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
*/
//虽然可以得到异常信息,但是没法返回修改数据
System.out.println("异步任务成功完成:结果是:"+res+";异常是" + exc);
}).exceptionally(throwable -> {
//可以感知异常,同时返回默认值
/**
* @FunctionalInterface
public interface Function<T, R> {
R apply(T t);
*/
return 10;
});
System.out.println("exceptionally运行的结果:"+future.get());
System.out.println("main。。。。end..");
3.3 handle最终处理
代码测试:下面的代码测试涉及到java8新特性函数式接口
Java8新特性——核心——Lambda和Stream
Java8 引入了函数式接口,并在java.util.function 包内预定义了常用函数式接口,下表罗列了一些常用的函数式接口:
//我们自己创建的一个线程池
public static ExecutorService executor