代码之家  ›  专栏  ›  技术社区  ›  Soumya Simanta

将ActorRef传递给其他演员是好还是坏?

  •  27
  • Soumya Simanta  · 技术社区  · 10 年前

    我想弄清楚我通过Akka的习惯 ActorRef 围绕着其他演员并不是一种反模式。

    我的系统中有几个演员。有些是长寿的( restClientRouter , publisher )有些人在完成工作后死亡( geoActor ). 短期参与者需要向长期参与者发送消息,因此需要 参与者参考 s

      //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( restClientRouter 出版商 )到的构造函数 GeoInferenceActor 。这可以吗?有更好的方法吗?

    2 回复  |  直到 10 年前
        1
  •  25
  •   Community CDub    7 年前

    有两种好方法可以将参与者引用“介绍”给需要它们的参与者实例。

    1) 使用所需的ref作为构造函数args创建actor(这就是您正在做的)

    2) 创建实例后,通过消息传递所需的ref

    你的解决方案是完全可以接受的,甚至是Akka技术负责人Roland Kuhn在本文中提出的:

    Akka actor lookup or dependency injection

        2
  •  17
  •   Jean Logeart    10 年前

    Akka API documentation :

    ActorRef可以通过消息传递在参与者之间自由共享。

    在您的例子中,您将它们传递给构造函数,这是 绝对地 很好,而且应该是这样。