收到Future[httpResponse]
后,我尝试将邮件发送到sender
但我忘记了sender
的引用。
以下是我的接收方法的代码:
def receive = {
case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
// I have the correct sender reference
implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
// I have the correct sender reference
val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
println("http request sent")
// I have the correct sender reference
response onSuccess {
case HttpResponse(statusCode, _, entity, _) ⇒ {
entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
// NO Reference to sender
sender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
}
}
case _ => println("http request success 2")
}
response onFailure {
case exception: Throwable ⇒ {
println("http request failure")
throw exception
} // Adopting let-it-crash fashion by re-throwning the exception
}
}
case _ => println("I am httpConsumerActor and I don't know")
}
如果我改变这样的代码:
def receive = {
case Seq(method: HttpMethod, endpoint: String, payload: String) ⇒ {
// I have the correct sender reference
implicit val materializer: ActorMaterializer = ActorMaterializer(ActorMaterializerSettings(context.system)) // needed by singleRequest method below
// I have the correct sender reference
val response: Future[HttpResponse] = Http(context.system).singleRequest(HttpRequest(method = method, uri = endpoint, entity = payload))
println("http request sent")
// I have the correct sender reference
val mySender = sender
response onSuccess {
case HttpResponse(statusCode, _, entity, _) ⇒ {
entity.dataBytes.runFold(ByteString.empty)(_ ++ _).foreach { body ⇒
// NO Reference to sender
mySender ! HttpConsumerResponse(statusCode = statusCode, contentType = entity.contentType, body = body.utf8String)
}
}
case _ => println("http request success 2")
}
response onFailure {
case exception: Throwable ⇒ {
println("http request failure")
throw exception
} // Adopting let-it-crash fashion by re-throwning the exception
}
}
case _ => println("I am httpConsumerActor and I don't know")
}
一切正常,但我必须像这一行一样发送演员的引用,我知道这不是最好的方法:
val mySender = sender
答案 0 :(得分:6)
你的第一种方法不起作用的原因是你正在关闭可变状态",即执行onComplete时执行sender()
方法,并且不再包含引用。这是阿卡的一个相当常见的错误,我们都去过那里! :)
正确的解决方案,就像您已经发现的那样,是预先存储引用。还有其他选项,例如"成为"别的东西,但是为了你的使用我会说,预售是正确的方法,在" nice"之间进行权衡。和"简单"。
有关参考,请参阅以下资源:SO question,Blog post