异步编排(CompletableFuture异步调用)

1、问题背景

问题:当查询接口较复杂时候,数据的获取都需要远程调用,必然需要花费更多的时间。

假如查询文章详情页面,需要如下标注的时间才能完成:


// 1. 查询文章详情 0.5s

// 2. 查询文章博主个人信息 0.5s

// 3. 查询文章评论 1s

// 4. 查询博主相关文章分类 1s

// 5. 相关推荐文章 1s

// ......
上面的描述只是举个例子不要在意这里的查询描述,看实际情况使用,有些相关的查询我们可以拆分接口实现,上面的描述只是为了举例子。

那么,用户需要4s后才能统计的数据。很显然是不能接受的。

如果有多个线程同时完成这4步操作,也许只需要1s左右即可完成响应。

2、CompletableFuture介绍

在Java 8中, 新增加了一个包含50个方法左右的类: CompletableFuture,提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,提供了函数式编程的能力,可以通过回调的方式处理计算结果,并且提供了转换和组合CompletableFuture的方法。

CompletableFuture类实现了Future接口,所以你还是可以像以前一样通过get方法阻塞或者轮询的方式获得结果,但是这种方式不推荐使用。

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

在这里插入图片描述

2.1 创建异步对象

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

static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同。

  • runAsync方法不支持返回值。
  • supplyAsync可以支持返回值。

2.2 计算完成时回调方法

当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action);
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action);
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor);

public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn);

whenComplete可以处理正常和异常的计算结果,exceptionally处理异常情况。BiConsumer<? super T,? super Throwable>可以定义处理业务

whenComplete 和 whenCompleteAsync 的区别:

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

方法不以Async结尾,意味着Action使用相同的线程执行,而Async可能会使用其他线程执行(如果是使用相同的线程池,也可能会被同一个线程选中执行)

2.3 线程串行化方法

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

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

thenRun方法:只要上面的任务执行完成,就开始执行thenRun,只是处理完任务后,执行 thenRun的后续操作

带有Async默认是异步执行的。这里所谓的异步指的是不在当前线程内执行。

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

Function<? super T,? extends U>

T:上一个任务返回结果的类型

U:当前任务的返回值类型

2.4 多任务组合

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs);

public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs);

allOf:等待所有任务完成

anyOf:只要有一个任务完成

3、例子

查询文章详情demo

@Service
public class ArticleService {
	@Autowired
    private ArticleClient articleClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    
 	public ItemVo load(Long id) {
	// 1. 查询文章详情 0.5s
	// 下面的查询需要用到文章对应的发布用户,所以这里需要使用CompletableFuture.supplyAsync
	CompletableFuture<ArticleEntity> articleCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ResponseVo<ArticleEntity> skuEntityResponseVo = this.articleClient.getArticleById(id);
            ArticleEntity articleEntity = skuEntityResponseVo.getData();
            if (articleEntity == null) {
                return null;
            }
            itemVo.setId(id);
            itemVo.setTitle(articleEntity.getTitle());
            itemVo.setDefaltImage(articleEntity.getDefaultImage());
            return articleEntity;
        }, threadPoolExecutor);
	// 2. 查询文章博主个人信息 0.5s
	// 这里查询需要依赖文章关联的用户id,所以需要使用articleCompletableFuture.thenAcceptAsync()
    CompletableFuture<Void> userCompletableFuture = articleCompletableFuture.thenAcceptAsync(articleEntity -> {
        ResponseVo<UserEntity> categoryResponseVo = this.userClient.queryUserInfoById(articleEntity.getUserId());
        UserEntity userEntity = categoryResponseVo.getData();
        itemVo.setUserInfo(userEntity);
    }, threadPoolExecutor);    
	// 3. 查询博主相关文章分类 1s
	// 这里查询需要依赖文章关联的用户id,所以需要使用articleCompletableFuture.thenAcceptAsync()
    CompletableFuture<Void> userOtherArticleCompletableFuture = articleCompletableFuture.thenAcceptAsync(articleEntity -> {
        ResponseVo<List<UserAuserOtherArticleEntity>> categoryResponseVo = this.articleClient.queryUserAuserOtherArticleById(articleEntity.getUserId());
        UserAuserOtherArticleEntity userAuserOtherArticleEntity = categoryResponseVo.getData();
        itemVo.setUserAuserOtherArticleList(userAuserOtherArticleEntity);
    }, threadPoolExecutor);
    // 4. 查询文章评论 1s
    // 不需要依赖其他请求返回值,可以使用新的异步对象 CompletableFuture.runAsync()
    CompletableFuture<Void> commentsCompletableFuture =  CompletableFuture.runAsync(() -> {
        ResponseVo<List<UserArticleCategoryEntity>> userArticleCategoryVo = this.userClient.queryCommentsByArticleId(id);
        UserArticleCategoryEntity userArticleCategoryEntity = userArticleCategoryVo.getData();
        itemVo.setUserArticleCategoryList(userArticleCategoryEntity);
    }, threadPoolExecutor);
	// 5. 相关推荐文章 1s
	// 不需要依赖其他请求返回值,可以使用新的异步对象 CompletableFuture.runAsync()
	CompletableFuture<Void> relatedArticlesCompletableFuture =  CompletableFuture.runAsync(() -> {
        ResponseVo<List<RelatedArticlesEntity>> userArticleCategoryVo = this.articleClient.queryRelatedArticles(id);
        UserArticleCategoryEntity userArticleCategoryEntity = userArticleCategoryVo.getData();
        itemVo.setUserArticleCategoryList(userArticleCategoryEntity);
    }, threadPoolExecutor);
	}
	// 多任务执行组合 CompletableFuture.allOf()
	CompletableFuture.allOf(articleCompletableFuture, userCompletableFuture, userOtherArticleCompletableFuture,
                commentsCompletableFuture, relatedArticlesCompletableFuture).join();
     return itemVo;
}

添加线程池配置类:

@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(
            @Value("${thread.pool.coreSize}")Integer coreSize,
            @Value("${thread.pool.maxSize}")Integer maxSize,
            @Value("${thread.pool.keepalive}")Integer keepalive,
            @Value("${thread.pool.blockQueueSize}")Integer blockQueueSize
    ){
        return new ThreadPoolExecutor(coreSize, maxSize, keepalive, TimeUnit.SECONDS, new ArrayBlockingQueue<>(blockQueueSize));
    }
}

在application.yml中添加线程池配置:

thread:
  pool:
    coreSize: 100
    maxSize: 500
    keepalive: 60
    blockQueueSize: 1000

上面例子完美呈现,计算完成时回调方法CompletableFuture.supplyAsync()、线程串行化方法articleCompletableFuture.thenAcceptAsync()、创建异步对象CompletableFuture.runAsync()、多任务组合CompletableFuture.allOf()

异步编排是指在复杂的处理流程中,使用一些异步处理的手段来提高效率和性能。在这种场景下,ThreadLocal可能会出现获取失败的问题。ThreadLocal主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式,而不是用来解决对象共享访问问题。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确地访问到自己的对象。通过将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,可以在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。异步编排和ThreadLocal在处理复杂的流程时可以结合使用,通过ThreadLocal来保存和访问各个线程的对象,从而实现异步处理的目的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [ThreadLocal跨线程问题](https://download.csdn.net/download/weixin_38669881/13750353)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [ThreadLocal和同步异步的解释](https://blog.csdn.net/doom20082004/article/details/53612339)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [异步 多线程 线程池 异步编排 ThreadLocal的使用](https://blog.csdn.net/weixin_45552441/article/details/125605532)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值