[英]Processing an akka stream asynchronously and writing to a file sink
我正在嘗試編寫一段代碼,這些代碼將消耗代碼行(公司的股票交易所代碼)流,並從REST API中為每個代碼行獲取公司信息。
我想異步獲取多個公司的信息。
我想以連續的方式將結果保存到文件中,因為整個數據集可能不適合內存。
在我能夠在這個主題上搜索到的關於akka流和資源的文檔之后,我提出了以下代碼(為簡潔起見,省略了一些部分):
implicit val actorSystem: ActorSystem = ActorSystem("stock-fetcher-system")
implicit val materializer: ActorMaterializer = ActorMaterializer(None, Some("StockFetcher"))(actorSystem)
implicit val context = system.dispatcher
import CompanyJsonMarshaller._
val parallelism = 10
val connectionPool = Http().cachedHostConnectionPoolHttps[String](s"api.iextrading.com")
val listOfSymbols = symbols.toList
val outputPath = "out.txt"
Source(listOfSymbols)
.mapAsync(parallelism) {
stockSymbol => Future(HttpRequest(uri = s"https://api.iextrading.com/1.0/stock/${stockSymbol.symbol}/company"), stockSymbol.symbol)
}
.via(connectionPool)
.map {
case (Success(response), _) => Unmarshal(response.entity).to[Company]
case (Failure(ex), symbol) => println(s"Unable to fetch char data for $symbol") "x"
}
.runWith(FileIO.toPath(new File(outputPath).toPath, Set(StandardOpenOption.APPEND)))
.onComplete { _ =>
bufferedSource.close
actorSystem.terminate()
}
這是有問題的行:
runWith(FileIO.toPath(new File(outputPath).toPath, Set(StandardOpenOption.APPEND)))
不會編譯,編譯器給了我這個神秘的錯誤:
Type mismatch, expected Graph[SinkShape[Any, NotInferedMat2], actual Sink[ByeString, Future[IOResult]]
如果將接收器更改為Sink.ignore或println(_),它將起作用。
我希望得到一些更詳細的解釋。
正如編譯器所指示的,類型不匹配。 在對.map
的調用中...
.map {
case (Success(response), _) =>
Unmarshal(response.entity).to[Company]
case (Failure(ex), symbol) =>
println(s"Unable to fetch char data for $symbol")
"x"
}
...您將返回Company
實例或String
,因此編譯器將最接近的超類型(或“最小上限”)推斷為Any
。 Sink
需要類型為ByteString
輸入元素,而不是Any
。
一種方法是將響應發送到文件接收器,而無需解組響應:
Source(listOfSymbols)
.mapAsync(parallelism) {
...
}
.via(connectionPool)
.map(_.entity.dataBytes) // entity.dataBytes is a Source[ByteString, _]
.flatMapConcat(identity)
.runWith(FileIO.toPath(...))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.