传递ActorRef给其他Actor是好还是坏?

27

我正在尝试确定将Akka ActorRef 传递给其他actor的用法是否不是反模式。

我的系统中有一些actor。其中一些是长期存在的 (restClientRouter,publisher),而有些在完成工作后就消失了 (geoActor)。短期存在的actors需要向长期存在的actors发送消息,因此需要它们的ActorRef

  //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")

你可以看到我正在将ActorRefs (restClientRouterpublisher) 传递给GeoInferenceActor的构造函数。这样做可以吗?是否有更好的方法?

2个回答

25
有几种好的方法可以将演员引用“介绍”给需要它们的演员实例。 1)创建带有它所需的引用作为构造函数参数的演员(这是您正在做的) 2)在实例创建后通过消息传递所需的引用
您的解决方案是完全可接受的,甚至建议由Akka的技术负责人Roland Kuhn在此帖子中提到:Akka actor lookup or dependency injection

17

Akka API文档所述,这是完全有效的:

ActorRefs可以通过消息传递在演员之间自由共享。

在您的情况下,您将它们传递给构造函数,这是绝对正常的做法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接