在我的專案中,我必須撰寫一個休息客戶端,它將從休息服務接收一個 HttpResponse 作為未來。我想要的是記錄回應的狀態代碼,如果出現任何例外,也要記錄該例外。我怎樣才能使用管道模式來實作這一點。PFB 我的代碼片段:
class MetadataAggregator(implicit config: Config) extends Actor with ActorLogging {
import context.system
import akka.pattern.pipe
implicit val exec = context.system.dispatcher
val url = sys.env.getOrElse("URL", config.getString("conf.url"))
override def receive: Receive = {
case MetadataEvent(event, phase, topic) =>
val payload = captureMetadata(event, phase, topic)
publishMetadata(payload)
case _ => //Do nothing
}
def publishMetadata(payload: String) = {
log.info(s"Metadata payload : $payload")
val responseFuture = Http().singleRequest(
HttpRequest(
HttpMethods.POST,
uri = url,
entity = HttpEntity(
ContentTypes.`application/json`,
payload
)
)
)
responseFuture.pipeTo(self)
}
override def supervisorStrategy: SupervisorStrategy = OneForOneStrategy() {
case ex: RuntimeException =>
log.error(s"${self.path} incurred an exception. $ex...")
ex.printStackTrace()
log.info("Resuming...")
Resume
case any: Any =>
log.error(s"${self.path} stopping due to $any ...")
any.printStackTrace()
Stop
}
}
Bdw,我不能使用 akka 型別化的actor,因為整個專案都在使用非型別化的actor。
uj5u.com熱心網友回復:
該pipeTo呼叫正在將 發送HttpResponse給參與者,因此您需要在receive方法中處理它。但我建議創建一條包含有效負載和回應的新訊息,并將其發送到self. 這允許您描述導致回應的負載。
HttpResponse正在被捕獲并忽略,因此case _ =>記錄任何意外訊息通常是一個好主意,以便更早地捕獲此類事情。
示例代碼:
為結果創建一個新類:
case class PublishResult(payload: String, result: Try[HttpResponse])
在publishMetadata:
val responseFuture = Http().singleRequest(???)
responseFuture.onComplete{ res =>
self ! PublishResult(payload, res)
}
在receive添加這個處理程式:
case PublishResult(payload, res) =>
res match {
case Failure(e) =>
log.warn("Request payload {} failed: {}", payload, e.getMessage)
case Success(response) =>
log.debug("Request succeeded")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/413849.html
標籤:
上一篇:如何使用影像的升序日期時間訂購.jpg檔案是在scala中捕獲的時間
下一篇:如何在Scala中創建泛型類
