我試圖使用流,而不是純粹的演員來處理HTTP請求和我用下面的代碼來:如何綁定akka http與akka流?
trait ImagesRoute {
val log = LoggerFactory.getLogger(this.getClass)
implicit def actorRefFactory: ActorRefFactory
implicit def materializer: ActorMaterializer
val source =
Source
.actorRef[Image](Int.MaxValue, OverflowStrategy.fail)
.via(Flow[Image].mapAsync(1)(ImageRepository.add))
.toMat(Sink.asPublisher(true))(Keep.both)
val route = {
pathPrefix("images") {
pathEnd {
post {
entity(as[Image]) { image =>
val (ref, publisher) = source.run()
val addFuture = Source.fromPublisher(publisher)
val future = addFuture.runWith(Sink.head[Option[Image]])
ref ! image
onComplete(future.mapTo[Option[Image]]) {
case Success(img) =>
complete(Created, img)
case Failure(e) =>
log.error("Error adding image resource", e)
complete(InternalServerError, e.getMessage)
}
}
}
}
}
}
}
我不知道這是,或者即使做了正確的方法這是一個好方法,或者如果我應該使用演員與路線進行交互,使用問題模式,然後在演員內部進行流式傳輸。
任何想法?
如果我沒有記錯的話,你的情況你根本不需要流。據我所知,'ImageRepository.add'方法返回一個'Future';所有你需要做的就是編寫'onComplete(ImageRepository.add(image))',就這些了。 –
@VladimirMatveev是的沒錯,這只是一個簡單的例子,但流管道應該做更多的事情,比如聯繫外部資源並最終回壓東西...... –