作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
收到 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")
}
一切正常,但我必须像这条线一样发送 Actor 的引用,我知道这不是最好的方法:
val mySender = sender
最佳答案
您的第一种方法不起作用的原因是您“关闭了可变状态”,即在执行 onComplete 时执行 sender()
方法,并且不再包含引用.这是 Akka 中一个相当常见的错误,我们都经历过! :)
正确的解决方案是预先存储引用,正如您自己已经发现的那样。还有其他选项,例如“成为”其他东西,但为了您的使用,我会说预存储是在“好”和“简单”之间权衡的正确方法。
有关引用,请参阅以下资源:SO question , Blog post
关于scala - Akka http 丢失发件人引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407706/
我是一名优秀的程序员,十分优秀!