Akka actorFor vs passing an ActorRef

2019-04-03 19:04发布

I'm learning Akka and I'm trying to figure out how to get actors talking to each other (let's call them A and B). It's not a request / response scenario, A and B are sending each other messages at any time.

At the moment I've got two sibling actors that pass messages in both directions to each other. They're both created directly on the ActorSystem. I had initially passed the ActorRef of A into the constructor of B. But I can't pass the ActorRef of B to the constructor of A because it doesn't exist yet, i.e. I can't use this method for circular references.

I've been reading about actorFor and this would let me look up an actor using it's path. However, I'm not comfortable with this setup, because if the path changes, it won't be caught by the compiler.

Another alternative, considering every actor has access to it's parent, is to pass the messages from A and B to the parent and then have the parent pass the message back down to A and B. But this couples the parent to the message types being passed back and forth.

What are strategies are people using for making actors aware of each other? Am I being too cautious about looking up actors by path?

标签: scala akka
1条回答
Bombasti
2楼-- · 2019-04-03 19:35

In my humble opinion you have three strategies, which I list from the closer to your problem (but also to me the worst pattern, I am sorry)

Strategy 1: you create actor A and actor B, passing actorRef A to the constructor of actor B. Your ping-pong will start from actor B sending a message to actor A, and actor A can simply reply using the sender reference. (or the other way around)


Strategy 2: you create a layer in your application which takes care of the naming: it assigns the name at creation of the actor, as well as when querying. This centralizes the problem in a single point.


Strategy 3: You wonder if two siblings actors playing ping-pong are not replacing a better, more modular actor hierarchy where basically each actor communicate only with his parent and his children and has no knowledge about his siblings.

查看更多
登录 后发表回答