Akka Streams异步流无法异步运行,需要进行哪些额外配置?
问题原因分析
1. .async() 写法测试的问题
Akka Streams 中的 .async() 作用是将上下游算子拆分为独立的Actor运行,实现不同算子间的异步执行,但同一个算子内部的元素处理默认仍是串行的:你定义的takePart Flow虽然加了async标记,但处理完元素A之后才会开始处理元素B,4个元素每个阻塞3秒,总耗时自然就是12秒,没有并行效果。
2. mapAsync 写法测试的问题
你写的blocking函数逻辑存在错误:阻塞操作Thread.sleep(3000)是在mapAsync的调用线程中同步执行的,执行完才会返回一个已经完成的CompletableFuture。mapAsync的并行能力依赖返回的CompletionStage是异步执行的,这种写法等于把异步逻辑写成了同步阻塞,自然还是串行执行,总耗时12秒。
正确实现方案
修正后的mapAsync写法
把阻塞逻辑放到CompletableFuture的异步执行上下文里即可触发并行:
Function<String, CompletionStage<String>> blocking = s -> CompletableFuture.supplyAsync(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return s; }); Source.from(List.of("A", "B", "C", "D")) .mapAsync(4, blocking) .toMat(Sink.fold("", (arg1, arg2) -> arg1), Keep.right()) .run(actorSystem) .toCompletableFuture() .join();
该写法下4个元素的阻塞逻辑会并行执行,总耗时会降到3秒左右。
普通算子并行实现方案
如果要让普通的map逻辑也实现并行处理,可以将每个元素拆分为单独Source后合并:
Source.from(List.of("A", "B", "C", "D")) .flatMapMerge(4, s -> Source.single(s) .map(str -> { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } return str; }) .async()) .toMat(Sink.fold("", (arg1, arg2) -> arg1), Keep.right()) .run(actorSystem) .toCompletableFuture() .join();
额外配置建议
如果你的业务逻辑属于阻塞型(比如IO操作、CPU密集计算),不要使用Akka默认的fork-join dispatcher,避免占用Akka核心调度线程。建议在application.conf中单独定义固定大小的线程池dispatcher:
blocking-dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 10 } throughput = 1 }
使用时给对应的算子指定dispatcher即可:.withAttributes(ActorAttributes.dispatcher("blocking-dispatcher"))
内容的提问来源于stack exchange,提问作者minizibi
相关产品推荐
相关产品推荐

