【发布时间】:2020-11-17 17:10:42
【问题描述】:
所以我正在尝试使用 Akka Streams 计算项目的出现次数。 下面的示例是我所拥有的简化版本。我需要两个管道同时工作。由于某种原因,打印的结果不正确。
有人知道为什么会这样吗?我是否遗漏了有关子流的重要内容?
/**
* SIMPLE EXAMPLE
*/
object TestingObject {
import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl._
import java.nio.file.Paths
import akka.util.ByteString
import counting._
import graph_components._
// implicit actor system
implicit val system:ActorSystem = ActorSystem("Sys")
def main(args: Array[String]): Unit = {
val customFlow = Flow.fromGraph(GraphDSL.create() {
implicit builder =>
import GraphDSL.Implicits._
// Components
val A = builder.add(Balance[(Int, Int)](2, waitForAllDownstreams = true));
val B1 = builder.add(mergeCountFold.async);
val B2 = builder.add(mergeCountFold.async);
val C = builder.add(Merge[(Int, Int)](2));
val D = builder.add(mergeCountReduce);
// Graph
A ~> B1 ~> C ~> D
A ~> B2 ~> C
FlowShape(A.in, D.out);
})
// Run
Source(0 to 101)
.groupBy(10, x => x % 4)
.map(x => (x % 4, 1))
.via(customFlow)
.mergeSubstreams
.to(Sink.foreach(println)).run();
}
def mergeCountReduce = Flow[(Int, Int)].reduce((l, r) => {
println("REDUCING");
(l._1, l._2 + r._2)
})
def mergeCountFold = Flow[(Int, Int)].fold[(Int,Int)](0,0)((l, r) => {
println("FOLDING");
(r._1, l._2 + r._2)
})
}
【问题讨论】:
-
您将
mergeCountReduce的哪些用法替换为mergeCountFold -
“仅输出部分结果项”和“错过元组的第一个值”究竟是什么意思?请注意,在您的示例中,
fold和reduce之间的区别在于,fold将发出最后一个看到的值的_1,而reduce将发出第一个看到的值的_1。由于这些都依赖于订购,还值得注意的是Balance和Merge组合(尤其是在两者之间的async)不提供真正的订购保证。 -
我正在替换这两种用法,我正在或正在使用 mergeCountReduce 或 mergeCountFold,没有混合。
-
“只有一些值”是指应该打印合并结果的接收器在使用 Reduce 时不会打印所有结果。使用 Fold 时,它会打印所有结果,但其中一些结果为 0 作为 ._1
-
排序并不重要,因为我之后将所有内容与 mergcountReduce/Fold 合并
标签: scala akka-stream