gpt4 book ai didi

scala - Akka 流 : Can not write to file sink

转载 作者:行者123 更新时间:2023-12-05 08:42:36 24 4
gpt4 key购买 nike

我正在尝试运行一个简单的 Akka Stream File Sink 示例,但没有成功。我可以创建一个 Source,运行 Flow,然后创建一个文件,但 ByteString 没有写入文件。而如果我尝试将流输出打印到控制台,我可以这样做。我在这里遗漏了什么吗?

import akka.stream._ 
import akka.stream.scaladsl._
import akka.{ NotUsed, Done}
import akka.actor.ActorSystem
import akka.util.ByteString
import scala.concurrent._
import scala.concurrent.duration._
import java.nio.file.Paths

object First extends App {

val source: Source[Int, NotUsed] = Source ( 1 to 100)

implicit val system = ActorSystem("QuickStart")
implicit val materializer = ActorMaterializer()

// works: prints 1-100
//source.runForeach(println) (materializer)

val factorials = source.scan(BigInt(1))((acc,next) => acc * next)

// there is no content in the Sink (file)
/**val result =
factorials
.map(num => ByteString(s"${num}\n"))
.runWith(FileIO.toPath(Paths.get("factorials.txt")))
**/

def lineSink(fileName: String): Sink[String, Future[IOResult]] =
Flow[String]
.map(s => ByteString(s + "\n"))
.toMat(FileIO.toPath(Paths.get(fileName))) (Keep.right)

//There is no content in the Sink.
factorials.map(_.toString).runWith(lineSink("factorials.txt"))

system.terminate()

}

build.sbt 有:

name := "akkaGuide"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-stream" % "2.4.10"
)

提前感谢您的宝贵时间。

最佳答案

我认为您可能终止得太早了。尝试等到 Future 完成:

val result = factorials.map(_.toString).runWith(lineSink("factorials.txt"))
import system.dispatcher
result.onComplete { _ => system.terminate() }

关于scala - Akka 流 : Can not write to file sink,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com