Identify Akka HttpRequest and HttpResponse?



在使用AkkaHttpRequest并将请求通过管道发送给actor时,我无法识别响应。 参与者将处理将收到的每条消息,但它不知道哪个请求用于获取此响应。有没有办法识别每个请求以匹配响应?

注意:我没有服务器再次重新发送请求正文的任何部分。

提前致谢

MySelf.scala

import akka.actor.{ Actor, ActorLogging }
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.{ ActorMaterializer, ActorMaterializerSettings }
import akka.util.ByteString
class Myself extends Actor with ActorLogging {
import akka.pattern.pipe
import context.dispatcher
final implicit val materializer: ActorMaterializer = 
ActorMaterializer(ActorMaterializerSettings(context.system))
def receive = {
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
entity.dataBytes.runFold(ByteString(""))(_ ++ _).foreach { body =>
log.info("Got response, body: " + body.utf8String)
}
case resp @ HttpResponse(code, _, _, _) =>
log.info("Request failed, response code: " + code)
resp.discardEntityBytes()
}
}

Main.scala

import akka.actor.{ActorSystem, Props}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
object HttpServerMain extends App {
import akka.pattern.pipe
//  import system.dispatcher
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
// needed for the future flatMap/onComplete in the end
implicit val executionContext = system.dispatcher
val http = Http(system)
val myActor = system.actorOf(Props[MySelf])
http.singleRequest(HttpRequest(uri = "http://akka.io"))
.pipeTo(myActor)
http.singleRequest(HttpRequest(uri = "http://akka.io/another-request"))
.pipeTo(myActor)
Thread.sleep(2000)
system.terminate()

您可以简单地使用map来转换Future,并在将其通过管道传输到myActor之前向其添加某种 ID(通常用于此类目的通常称为相关 ID(:

http.singleRequest(HttpRequest(uri = "http://akka.io"))
.map(x => (1, x)).pipeTo(myActor)

您需要更改模式匹配块才能进行更新:

case (id, HttpResponse(StatusCodes.OK, headers, entity, _)) =>

如果您由于某种原因不能/不想更改模式匹配块,则可以使用相同的方法,而是将唯一的 HTTP 标头添加到已完成的请求(使用copy(中,如下所示(如果编译则不检查(:

// make a unique header name that you are sure will not be
// received from http response:
val correlationHeader: HttpHeader = ... // mycustomheader
// Basically hack the response to add your header:
http.singleRequest(HttpRequest(uri = "http://akka.io"))
.map(x => x.copy(headers = correlationHeader +: headers)).pipeTo(myActor)
// Now you can check your header to see which response that was:
case HttpResponse(StatusCodes.OK, headers, entity, _) =>
headers.find(_.is("mycustomheader")).map(_.value).getOrElse("NA")

不过,与以前的选项相比,这更像是一个黑客,因为您正在修改响应。

我认为您不能直接使用pipeTo来做到这一点,因为它本质上只是将andThen调用添加到您的Future中。一种选择是map,然后将(request, response)元组发送给 actor:

val request = HttpRequest(uri = "http://akka.io")
http.singleRequest(request).map {
response => myActor ! (request, response)
}
class Myself extends Actor with ActorLogging {
...
def receive = {
case (request, HttpResponse(StatusCodes.OK, headers, entity, _)) =>
...
case (request, resp @ HttpResponse(code, _, _, _)) =>
log.info(request.toString)
...
}
}

最新更新