Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 确定Akka HttpRequest和HttpResponse?_Scala_Http_Akka_Akka Http - Fatal编程技术网

Scala 确定Akka HttpRequest和HttpResponse?

Scala 确定Akka HttpRequest和HttpResponse?,scala,http,akka,akka-http,Scala,Http,Akka,Akka Http,使用AkkaHttpRequest并将请求传递给参与者时,我无法识别响应。 参与者将处理将接收到的每条消息,但不知道用于获取此响应的请求。有没有办法识别每个请求以匹配响应 注意:我没有服务器再次重新发送请求正文的任何部分 提前谢谢 斯卡拉先生 梅因斯卡拉酒店 您只需使用map转换未来,并在将其导入myActor之前向其添加某种ID(通常称为相关ID): http.singleRequest(HttpRequest(uri = "http://akka.io")) .map(x =>

使用AkkaHttpRequest并将请求传递给参与者时,我无法识别响应。 参与者将处理将接收到的每条消息,但不知道用于获取此响应的请求。有没有办法识别每个请求以匹配响应

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

提前谢谢

斯卡拉先生 梅因斯卡拉酒店
您只需使用
map
转换
未来
,并在将其导入
myActor
之前向其添加某种ID(通常称为相关ID):

http.singleRequest(HttpRequest(uri = "http://akka.io"))
    .map(x => (1, x)).pipeTo(myActor)
您需要更改模式匹配块以获取元组:

case (id, HttpResponse(StatusCodes.OK, headers, entity, _)) =>
如果出于某种原因您不能/不想更改模式匹配块,您可以使用相同的方法,但可以使用类似以下内容(如果编译,则不检查):


与之前的选项相比,这更像是一种黑客行为,因为您正在修改响应。

我认为您不能直接使用
pipeTo
,因为它本质上只是
然后调用您的
未来。一个选项是
映射
,然后向参与者发送
(请求、响应)
元组:

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)
      ...
  }
}

谢谢@yǝsʞǝlA的回答,但是对于第二种选择,你能解释一下吗more@MohamedElkady我更新了我的答案以澄清第二个选项。不确定它是否编译-我手头没有要测试的项目。
case (id, HttpResponse(StatusCodes.OK, headers, entity, _)) =>
// 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")
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)
      ...
  }
}