【发布时间】:2018-12-11 18:13:16
【问题描述】:
我正在使用 Akka Http 和 Akka Streams 开发一个客户端-服务器应用程序。 主要思想是服务器必须使用来自 Akka 流的 Source 来提供 http 响应。
问题是服务器在向客户端发送第一条消息之前积累了一些元素。但是,我需要服务器在源生成新元素后立即将元素发送到元素。
代码示例:
case class Example(id: Long, txt: String, number: Double)
object MyJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol {
implicit val exampleFormat = jsonFormat3(Test)
}
class BatchIterator(batchSize: Int, numberOfBatches: Int, pause: FiniteDuration) extends Iterator[Array[Test]]{
val range = Range(0, batchSize*numberOfBatches).toIterator
val numberOfBatchesIter = Range(0, numberOfBatches).toIterator
override def hasNext: Boolean = range.hasNext
override def next(): Array[Test] = {
println(s"Sleeping for ${pause.toMillis} ms")
Thread.sleep(pause.toMillis)
println(s"Taking $batchSize elements")
Range(0, batchSize).map{ _ =>
val count = range.next()
Test(count, s"Text$count", count*0.5)
}.toArray
}
}
object Server extends App {
import MyJsonProtocol._
implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()
.withFramingRenderer(
Flow[ByteString].intersperse(ByteString(System.lineSeparator))
)
implicit val system = ActorSystem("api")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
def fetchExamples(): Source[Array[Test], NotUsed] = Source.fromIterator(() => new BatchIterator(5, 5, 2 seconds))
val route =
path("example") {
complete(fetchExamples)
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 9090)
println("Server started at localhost:9090")
StdIn.readLine()
bindingFuture.flatMap(_.unbind()).onComplete(_ ⇒ system.terminate())
}
那么,如果我执行:
curl --no-buffer localhost:9090/example
我同时获取所有元素,而不是每 2 秒接收一个元素。
知道如何“强制”服务器发送从源中出来的每个元素吗?
【问题讨论】:
-
如果理解正确,您希望服务器对单个请求发送多个响应。这不是 HTTP 支持的东西——你需要一个类似 websocket 的东西。 doc.akka.io/docs/akka-http/current/server-side/… 详细介绍了 Akka-HTTP 中对 websocket 的支持。
-
感谢@Astrid 的建议。我找到了其他选择doc.akka.io/docs/akka-http/current/server-side/…
-
顺便说一句,一个HTTP请求可以有多个响应:en.wikipedia.org/wiki/Chunked_transfer_encoding
标签: scala akka akka-stream akka-http