我的问题是我有未知数量的组,并且如果mapAsync的并行数小于我得到的组数并且最后一个接收器中出现错误
Tearing down SynchronousFileSink(/Users/sam/dev/projects/akka-streams/target/log-ERROR.txt) due to upstream error (akka.stream.impl.StreamSubscriptionTimeoutSupport$$anon$2)
我尝试按照 akka 流模式指南 http://doc.akka.io/docs/akka-stream-and-http-experimental/1.0/scala/stream-cookbook.html 中的建议在中间放置一个缓冲区。
groupBy {
case LoglevelPattern(level) => level
case other => "OTHER"
}.buffer(1000, OverflowStrategy.backpressure).
// write lines of each group to a separate file
mapAsync(parallelism = 2) {....
但结果相同
最佳答案
扩展 jrudolph 的评论,这是完全正确的......
在此实例中您不需要 mapAsync
。作为一个基本示例,假设您有一个元组源
import akka.stream.scaladsl.{Source, Sink}
def data() = List(("foo", 1),
("foo", 2),
("bar", 1),
("foo", 3),
("bar", 2))
val originalSource = Source(data)
然后您可以执行 groupBy 来创建 Source of Sources
def getID(tuple : (String, Int)) = tuple._1
//a Source of (String, Source[(String, Int),_])
val groupedSource = originalSource groupBy getID
每个分组的源都可以通过一张map
并行处理,不需要任何花哨的东西。以下是每个分组在独立流中求和的示例:
import akka.actor.ActorSystem
import akka.stream.ACtorMaterializer
implicit val actorSystem = ActorSystem()
implicit val mat = ActorMaterializer()
import actorSystem.dispatcher
def getValues(tuple : (String, Int)) = tuple._2
//does not have to be a def, we can re-use the same sink over-and-over
val sumSink = Sink.fold[Int,Int](0)(_ + _)
//a Source of (String, Future[Int])
val sumSource =
groupedSource map { case (id, src) =>
id -> {src map getValues runWith sumSink} //calculate sum in independent stream
}
现在,所有 "foo"
数字与所有 "bar"
数字并行求和。
Future[T]
的封装函数并且您尝试发出一个 T
时,使用 mapAsync
;你问题中的情况并非如此。此外,mapAsync涉及waiting for results这不是 reactive ...
关于scala - 如何在akka流中使用mapAsync消费分组子流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32201457/