The right way to postpone messages in Akka

I am using akka cluster to do distributed computing in two pahses. First phaseA , then phaseB . For phase processing, I use akka FSM.

There is no tight synchronization, so one of the nodes can reach phaseB , while the others are still in phaseA .

The problem is that one of phaseB sends phaseB-related messages to others (they are still in phaseA ), which is why they lose phaseB-related messages.

Now I use a simple trick to postpone unknown messages:

 case any => self ! any 

But IMO is not the right way to do this. I know that I can also schedule any with the akka scheduler, but I don't like this either.

Here is the simplified code:

 package whatever import akka.actor._ object Test extends App { case object PhaseA case object PhaseB class Any extends Actor { def phaseA: Receive = { case PhaseA => { context.become(phaseB) println("in phaseB now") } case any => self ! any } def phaseB: Receive = { case PhaseB => println("got phaseB message !") } def receive = phaseA } val system = ActorSystem("MySystem") val any = system.actorOf(Props(new Any), name = "any") any ! PhaseB any ! PhaseA } 

What is the correct way to postpone messages in this situation?

+6
source share
1 answer

You can save messages for later processing. Mix akka.actor.Stash with your members and stash() your phaseB messages for later versions.

When your FSM is in phaseA and receives a phaseB message, call stash() . When this actor enters phaseB state, call unstashAll() and all saved messages will be unstashAll() .

+12
source

Source: https://habr.com/ru/post/981164/


All Articles