一、CompletableFuture 异步编排

1、业务场景

查询商品详情页的逻辑比较复杂,有些数据还需要远程调用,必然需要花费更多的时间。

java异步任务队列框架 java异步编排_java


假如商品详情页的每个查询,需要如下标注的时间才能完成 那么,用户需要 5.5s 后才能看到商品详情页的内容。很显然是不能接受的。 如果有多个线程同时完成这 6 步操作,也许只需要 1.5s 即可完成响应。

2、java8 - CompletableFuture

在 Java 8 中, 新增加了一个包含 50 个方法左右的类: CompletableFuture,提供了非常强大的 Future 的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合 CompletableFuture 的方法。 CompletableFuture 类实现了 Future 接口,所以你还是可以像以前一样通过get方法阻塞或者轮询的方式获得结果,但是这种方式不推荐使用。

CompletableFuture 和 FutureTask 同属于 Future 接口的实现类,都可以获取线程的执行结果。

java异步任务队列框架 java异步编排_java异步任务队列框架_02

2.1 创建异步对象

CompletableFuture 提供了四个静态方法来创建一个异步操作。

java异步任务队列框架 java异步编排_java异步任务队列框架_03

  • runXxxx 都是没有返回结果的,supplyXxx 都是可以获取返回结果的
  • 可以传入自定义的线程池,否则就用默认的线程池;
2.2 runAsync方法 - 无返回值
@Slf4j
public class Test01 {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        log.info("main...start...");
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            log.info("当前线程:{}",Thread.currentThread().getName());
        }, executor);
        log.info("main...end...");
    }
}

打印结果:

java异步任务队列框架 java异步编排_返回结果_04

2.3 supplyAsync方法 - 有返回值
@Slf4j
public class Test01 {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 2;
            log.info("运行结果:{}", i);
            return i;
        }, executor);
        // 获取结果
        Integer res = supplyAsync.get();
        log.info("获取结果:{}",res);
    }
}

打印结果:

java异步任务队列框架 java异步编排_返回结果_05

2.4 计算完成时回调方法

java异步任务队列框架 java异步编排_后端_06

whenComplete 可以处理正常和异常的计算结果,exceptionally 处理异常情况。

whenComplete 和 whenCompleteAsync 的区别:

whenComplete:是执行当前任务的线程执行继续执行 whenComplete 的任务。

whenCompleteAsync:是执行把 whenCompleteAsync 这个任务继续提交给线程池 来进行执行。

@Slf4j
public class Test01 {

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 0;
            log.info("运行结果:{}", i);
            return i;
        }, executor).whenComplete((res,exception)->{
            log.info("异步任务成功完成了,结果是:{},异常是:{}",res,exception);
        }).exceptionally(t->{
            // 可以感知异常,同时返回默认值
            return 10;
        });

        Integer integer = supplyAsync.get();
        log.info("获取结果:{}",integer);

    }
}

打印结果:

java异步任务队列框架 java异步编排_开发语言_07

2.5 handle方法

和 complete 一样,可对结果做最后的处理(可处理异常),可改变返回值。

/**
         * 方法执行完成后的处理
         */
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 5;
            log.info("运行结果:{}", i);
            return i;
        }, executor).handle((res,thr) ->{
            // 如果上一步的返回结果不为空,则将返回结果乘以2返回
            if(res != null){
                return res*2;
            }
            // 如果异常不为空,表示出现异常,则返回0
            if(thr != null){
                return 0;
            }
            return 0;
        });

        Integer integer = supplyAsync.get();
        log.info("获取结果:{}",integer);
2.6 线程串行化方法

java异步任务队列框架 java异步编排_返回结果_08

thenApply 方法:当一个线程依赖另一个线程时,获取上一个任务返回的结果,并返回当前 任务的返回值。

thenAccept 方法:消费处理结果。接收任务的处理结果,并消费处理,无返回结果。

thenRun 方法:只要上面的任务执行完成,就开始执行 thenRun,只是处理完任务后,执行 thenRun 的后续操作 带有 Async 默认是异步执行的,即开启一个新的线程执行该异步任务。同之前。

  • thenRun、thenRunAsync方法:不能获取到上一步的执行结果,无返回值
// thenRun方法
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 5;
            log.info("运行结果:{}", i);
            return i;
        }, executor).thenRun(() -> {
            log.info("执行任务2");
        });

// thenRunAsync:可指定自己的线程池
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 5;
            log.info("运行结果:{}", i);
            return i;
        }, executor).thenRunAsync(()->{
            log.info("执行任务2....");
        },executor);
  • thenAcceptAsync:可以获取上一步的执行结果,但是无返回值
CompletableFuture<Void> future = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 5;
            log.info("运行结果:{}", i);
            return i;
        }, executor).thenAcceptAsync(res->{
            log.info("任务2执行...上一步的执行结果:{}",res);
        },executor);

打印结果:

java异步任务队列框架 java异步编排_返回结果_09

  • thenApplyAsync:可以获取上一步的执行结果,有返回值并且以下一个任务的执行结果为返回值
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            log.info("当前线程:{}", Thread.currentThread().getId());
            int i = 10 / 5;
            log.info("运行结果:{}", i);
            return i;
        }, executor).thenApplyAsync(res -> {
            log.info("任务2开始执行....");
            return "hello " + res;
        }, executor);
        log.info("最终的返回结果:{}",future.get());
2.7 两任务组合 - 都要完成
  • runAfterBothAsync
    组合两个 future,不需要获取 future 的结果,只需两个 future 处理完任务后, 处理该任务
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
    log.info("任务2开始....");
    log.info("任务2结束....");
    return "hello";
}, executor);

// 任务1、任务2执行完成后,再执行任务3
future01.runAfterBothAsync(future02,()->{
	log.info("任务3开始....");
},executor);

打印结果:因为任务1和任务2是异步执行的,所以没有执行的先后顺序,但是任务3一定是在两个任务完成后才执行的

java异步任务队列框架 java异步编排_java_10

  • thenAcceptBothAsync:可以获取前两个任务的返回结果
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
    log.info("任务2开始....");
    log.info("任务2结束....");
    return "hello";
}, executor);

// 可以获取前两个任务的返回结果
future01.thenAcceptBothAsync(future02,(f1,f2)->{
	log.info("任务3,获取前两个任务的结果:{}---》{}",f1,f2);
},executor);

打印结果:

java异步任务队列框架 java异步编排_java_11

  • thenCombineAsync:可以接受前两个任务的返回值,并有返回值
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            log.info("任务2开始....");
            log.info("任务2结束....");
            return "hello";
        }, executor);

CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
            return f1 + " : " + f2 + "haha!";
        }, executor);
 log.info("任务3返回的结果:{}",future.get());

打印结果:

java异步任务队列框架 java异步编排_java异步任务队列框架_12

  • runAfterEitherAsync:两个任务,只要有一个完成,就执行任务3,不感知结果,自己业务返回值
CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            log.info("任务2开始....");
            try {
                Thread.sleep(3000);
                log.info("任务2结束....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, executor);

future01.runAfterEitherAsync(future02,()->{
            log.info("任务3...");
        },executor);
   log.info("mian....end....");

打印结果:

java异步任务队列框架 java异步编排_返回结果_13

  • acceptEitherAsync:感知结果,自己没有返回值
CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

        CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            log.info("任务2开始....");
            try {
                Thread.sleep(3000);
                log.info("任务2结束....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, executor);

        future01.acceptEitherAsync(future02,(res)->{
            log.info("任务3开始,返回的结果:{}",res);
        },executor);

打印结果:

java异步任务队列框架 java异步编排_后端_14

  • applyToEitherAsync: 感知结果,并有返回值
CompletableFuture<Object> future01 = CompletableFuture.supplyAsync(() -> {
            log.info("任务1开始....");
            int i = 10 / 5;
            log.info("任务1运行结果:{}", i);
            return i;
        }, executor);

CompletableFuture<Object> future02 = CompletableFuture.supplyAsync(() -> {
            log.info("任务2开始....");
            try {
                Thread.sleep(3000);
                log.info("任务2结束....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "hello";
        }, executor);

CompletableFuture<String> future = future01.applyToEitherAsync(future02, (res) -> {
            log.info("任务3执行...");
            return res.toString() + "haha";
        }, executor);
 log.info("任务3返回结果:{}",future.get());

打印结果:

java异步任务队列框架 java异步编排_返回结果_15

2.8 多任务组合

java异步任务队列框架 java异步编排_后端_16

allOf:等待所有任务完成

anyOf:只要有一个任务完成

java异步任务队列框架 java异步编排_java_17