问题描述
我有一个Actor,并且在某些消息中,我正在运行某种返回Future的方法。
I have a Actor, and on some message I'm running some method which returns Future.
def receive: Receive = {
case SimpleMessge() =>
val futData:Future[Int] = ...
futData.map { data =>
...
}
}
是否有可能通过实际的上下文来等待该数据?或者如果我在 SimpleMessage 中需要此数据,等待
是我能做的最好的事情?
Is it possible to pass actual context to wait for this data? Or Await
is the best I can do if I need this data in SimpleMessage?
推荐答案
如果您确实需要在处理下一条消息之前等待将来完成,则可以尝试以下操作:
If you really need to wait for the future to complete before processing the next message, you can try something like this:
object SimpleMessageHandler{
case class SimpleMessage()
case class FinishSimpleMessage(i:Int)
}
class SimpleMessageHandler extends Actor with Stash{
import SimpleMessageHandler._
import context._
import akka.pattern.pipe
def receive = waitingForMessage
def waitingForMessage: Receive = {
case SimpleMessage() =>
val futData:Future[Int] = ...
futData.map(FinishSimpleMessage(_)) pipeTo self
context.become(waitingToFinish(sender))
}
def waitingToFinish(originalSender:ActorRef):Receive = {
case SimpleMessage() => stash()
case FinishSimpleMessage(i) =>
//Do whatever you need to do to finish here
...
unstashAll()
context.become(waitingForMessage)
case Status.Failure(ex) =>
//log error here
unstashAll()
context.become(waitingForMessage)
}
}
在这种方法中,我们处理 SimpleMessage
,然后切换处理逻辑以存储所有后续的 SimpleMessage
,直到我们从未来得到结果为止。当我们获得结果时,无论失败与否,我们都会隐藏所有我们在等待未来时收到的所有 SimpleMessage
,并继续我们的快乐之路。
In this approach, we process a SimpleMessage
and then switch handling logic to stash all subsequent SimpleMessage
s received until we get a result from the future. When we get a result, failure or not, we unstash all of the other SimpleMessage
s we have received while waiting for the future and go on our merry way.
此参与者仅在两个状态之间来回切换,使您一次只能完全处理一个 SimpleMessage
阻止未来。
This actor just toggles back and forth between two states and that allows you to only fully process one SimpleMessage
at a time without needing to block on the Future.
这篇关于Actor中期货的执行上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!