我已经建立了一个定期查询API的Akka actor,如下所示:
echo (true) ? "yes" : "no"; //prints yes
echo (false) ? "yes" : "no"; //prints no
演员,实质上是:
val cancellable =
system.scheduler.schedule(0 milliseconds,
5 seconds,
actor,
QueryController(1))
我要做的是从object UpdateStatistics {
/**
* Query the controller for the given switch Id
*
* @param dpId Switch's Id
*/
case class QueryController(dpId: Int)
case object Stop
def props: Props = Props[UpdateStatistics]
}
class UpdateStatistics extends Actor with akka.actor.ActorLogging {
import UpdateStatistics._
def receive = {
case QueryController(id) =>
import context.dispatcher
log.info(s"Receiving request to query controller")
Future { FlowCollector.getSwitchFlows(1) } onComplete {
f => self ! f.get
}
case Stop =>
log.info(s"Shuting down")
context stop self
case json: JValue =>
log.info("Getting json response, computing features...")
val features = FeatureExtractor.getFeatures(json)
log.debug(s"Features: $features")
sender ! features
case x =>
log.warning("Received unknown message: {}", x)
}
}
演员那里获取json:Jvalue
消息。阅读Akka docs我认为这可能有用:
UpdateStatistics
但我不知道如何修改 implicit val i = inbox()
i.select() {
case x => println(s"Valor Devuelto $x")
}
println(i receive(2.second))
actor以便将结果发送到上面的收件箱。
我在文档中读到的另一个选项是event streams。
但我不认为这是正确的方法。
有没有办法实现我想做的事情?或者我是否需要使用我发送UpdateStatistics
响应的第二个Actor
?
答案 0 :(得分:4)
您可能正在寻找AKKA中的ask
模式。这将允许您将值返回给发件人。
import akka.pattern.ask
import akka.util.duration._
implicit val timeout = Timeout(5 seconds)
val future = actor ? QueryController(1)
val result = Await.result(future, timeout.duration).asInstanceOf[JValue]
println(result)
要使其发挥作用,您需要将回复发送到原始sender
,而不是self
。此外,在处理消息时,您应该注意将来关闭sender
的危险。