gpt4 book ai didi

scala - Akka http 丢失发件人引用

转载 作者:行者123 更新时间:2023-12-01 13:40:30 26 4
gpt4 key购买 nike

收到 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com