物化意味着产生结果graph https://doc.akka.io/docs/akka/current/stream/stream-graphs.html?language=scala
物化器使actors https://doc.akka.io/docs/akka/current/actors.html?language=scala执行图表以产生这些结果。
最简单形式的图由提供元素的源和消耗元素的接收器组成。
这是提供一系列整数的源(在本例中,整数是我们的元素):
val source = Source(1 to 10)
这是一个接收器,它将从源获取的所有整数相加:
val sink = Sink.fold[Int, Int](0)(_ + _)
我们连接源和接收器得到一个图:
val graph = source.toMat(sink)(Keep.right)
请注意没有计算在我们的例子中,加法是在创建图形时执行的。
代码是陈述性的 https://stackoverflow.com/questions/129628/what-is-declarative-programming,这些图描述了我们想要如何转换数据,但实际执行计算是其他人的工作:图是蓝图 https://doc.akka.io/docs/akka/current/stream/stream-flows-and-basics.html?language=scala#stream-materialization.
现在,物化器怎么样?当我们运行图表时,物化器会采取行动:
implicit val materializer = ActorMaterializer()
val futureResult = graph.run()
When we run()
图表,物化器获取图表并让参与者执行图表中指定的数据转换;在这个例子中,就是整数相加。
将图表想象为建造房屋的蓝图,将物化器想象为工头,看着蓝图,告诉建造者如何根据蓝图实际建造房屋,这可能会有所帮助。这个类比中的构建器对应于 Akka 中的参与者。
您的几段代码现在可以工作的原因是,通过物化器,您提供了一种执行图形的方法。图表大量用于阿卡 HTTP https://doc.akka.io/docs/akka-http/current/?language=scalaPlay 用于 HTTP 请求和响应。
The WSClient https://www.playframework.com/documentation/2.5.x/ScalaWS#Making-a-Request您在评论中提到使用图表来执行其请求,因此需要一个物化器。
这是创建和运行图表的完整示例:
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}
object Graphs extends App {
// The start of our simple graph. It provides elements, integers in our case
val source = Source(1 to 10)
// The end of our graph. It processes the source's elements
val sink = Sink.fold[Int, Int](0)(_ + _)
/*
* Connect source and sink.
* Keep only the output values (i.e., the graph's right side).
* Note that this is declarative: no result is computed until we run the graph.
*/
val graph = source.toMat(sink)(Keep.right)
// The system coordinates actors and provides threads for them
implicit val actorSystem = ActorSystem()
// The materializer makes actors execute graphs
implicit val materializer = ActorMaterializer()
// Running the graph means that the materializer assigns actors to execute
// the graph from start (source) to end (sink)
val futureResult = graph.run()
// Use the actor system's execution context, which provides threads,
// to print the result of running the graph
implicit val executionContext = actorSystem.dispatcher
futureResult.foreach(res => println(s"Result of running the graph: $res"))
actorSystem.terminate().foreach(_ => println("System is shut down"))
}
把这个放在你的build.sbt
使 Akka 的流库在您的代码中可用:
libraryDependencies += "com.typesafe.akka" %% "akka-stream" % "2.5.19"
这里还有更多 https://doc.akka.io/docs/akka/current/stream/stream-graphs.html?language=scala关于源和汇。