scala - 如何在akka流中使用mapAsync消费分组子流

标签 scala stream akka-stream

我需要做一些与此类似的事情https://github.com/typesafehub/activator-akka-stream-scala/blob/master/src/main/scala/sample/stream/GroupLogFile.scala

我的问题是我有未知数量的组,并且如果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/

相关文章:

rest - scalatra 在幕后使用抑扬符吗?

Scala 模式与 varargs 匹配

node.js - 为什么会错误地销毁流?

linux - 通过 wifi 流式传输音频 : feasible and how?

java - 将文件从 URL 流式传输到文件而不将其存储在内存中

scala - Akka HTTP Websocket,如何识别actor内部的连接

java - MongoSink 响应后提交给 kafka 消费者 - alpakka mongo 连接器

scala - CsvParser 不适用于缺少双引号的情况

scala - Akka Streams - 根据某些谓词拆分传入源数据

scala - Jodatime Scala 和序列化日期时间