简体   繁体   English

Actor消息的同步

[英]Synchronization of Actor messages

How is it possible to handle messages between actors to be executed and finished in a particular order? 如何处理要按特定顺序执行和完成的角色之间的消息?

In other words, if for example Message A wants to be received always before Message B , how it can be done using akka? 换句话说,例如,如果Message A要被前总是收到Message B ,用阿卡它可以怎么做?

I'll assume here that you mean you need a "Message A" to arrive before you can process a "Message B". 我在这里假设您的意思是您需要先获得“消息A”,然后才能处理“消息B”。 Other alternatives are: 其他替代方法是:

  • You want to receive any "Message A" before a "Message B" if the queue has both -- you cannot do this; 如果队列同时包含两个消息,则希望在“消息B”之前接收任何“消息A”。
  • You want "Message A" to be processed before "Message B" if they are sent in that order -- that is how it works already, from the same sender, and you can't do that if the senders are different. 如果要按“消息B”的顺序发送“消息A”,则希望在该消息之前对其进行处理-这是它已经从同一发件人发送的方式,如果发件人不同,则不能执行此操作。

So, having discarded these other options, here's a technique. 因此,放弃了这些其他选项之后,这是一种技术。 First, define separate receive methods for the state when Message A is expected and Message B is expected: 首先,为需要消息A和消息B的状态定义单独的接收方法:

def receivingA = Receive {
  case MessageA(x) => ...
}

def receivingB = Receive {
  case MessageB(y) => ...
}

You can set the first one as the default: 您可以将第一个设置为默认值:

def receive = receivingA

When receiving message A, you can change the state to expect message B: 收到消息A时,可以更改状态以期望消息B:

case MessageA(x) =>
  // do stuff
  become(receivingB)

And on message B you can go back to the first case, but I'll skip that. 在消息B上,您可以返回第一种情况,但是我将跳过。

Now the only thing missing is what you are going to do with messages arriving when not expected. 现在唯一缺少的是您将如何处理意外收到的消息。 You can do nothing, which will send them to the error log, or you can do something by overriding this method: 您什么也不能做,这会将它们发送到错误日志,或者可以通过重写此方法来做一些事情:

def unhandled(msg: Any): Unit = message match {
  case Terminated(target) => ...
  case msg => ...
}

The default behavior publishes unhandled message to the system event stream, as objects of type UnhandledMessage , so you could also get them that way, though that will just reinsert them into the queue under a different type. 默认行为将未处理的消息作为UnhandledMessage类型的对象发布到系统事件流,因此您也可以通过这种方式获取它们,尽管这只会将它们重新插入其他类型的队列中。 Finally, you could receive Message B out of order and queue it, then resend them once Message A is received. 最后,您可能会乱序接收消息B并将其排队,然后在收到消息A后重新发送它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM