Is passing around ActorRef to other Actors good or bad ?

微笑、不失礼 提交于 2019-12-20 11:11:06

问题


I'm trying to figure out if my usage of passing Akka ActorRef around to other actors is not an anti-pattern.

I've a few actors in my system. Some are long lived (restClientRouter,publisher) and some die after that they have done the work (geoActor). The short-lived actors need to send messages to the long-lived actors and therefore need their ActorRefs.

  //router for a bunch of other actors
  val restClientRouter = createRouter(context.system)

  //publishers messages to an output message queue
  val publisher: ActorRef = context.actorOf(Props(new PublisherActor(host, channel)), name = "pub-actor")     

  //this actor send a message to the restClientRouter and then sends the response
  //to the publisher 
  val geoActor = context.actorOf(Props(new GeoInferenceActor(restClientRouter, publisher)), name = "geo-inference-actor")

As you can see I'm passing the ActorRefs (restClientRouter and publisher) to the constructor of GeoInferenceActor. Is this okay or not? Is there a better way of doing this ?


回答1:


There are a couple of good ways to "introduce" actor refs to actor instances that need them.

1) Create the actor with the refs it needs as constructor args (which is what you are doing)

2) Pass in the needed refs with a message after the instance is created

Your solution is perfectly acceptable, and even suggested by Roland Kuhn, the Tech Lead for Akka, in this post:

Akka actor lookup or dependency injection




回答2:


It is perfectly valid, as stated in the Akka API documentation:

ActorRefs can be freely shared among actors by message passing.

In your case, you are passing them to the constructors, which is absolutely fine and the way it is supposed to be.



来源:https://stackoverflow.com/questions/24840608/is-passing-around-actorref-to-other-actors-good-or-bad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!