【问题标题】:Retrieving an ActorSelection from a Trait in akka/scala从 akka/scala 中的 Trait 中检索 ActorSelection
【发布时间】:2014-09-06 18:58:58
【问题描述】:

我是 scala/akka 的新手。我需要创建一个特征,并从这个特征中,从上下文或直接从 actorSystem 中检索演员。 但我不希望此 trait 扩展 Actor,也不想强制与 Actor 混合。

有没有办法做到这一点?

谢谢。

【问题讨论】:

    标签: scala akka actor traits


    【解决方案1】:

    欢迎来到 Akka :-)

    您应该使用抽象方法创建一个特征,该方法将用于检索演员系统,例如:

    trait DoesThings {
      def system: ActorSystem 
      def findActor(name: String) = // do actor selection using system here
    }
    
    object Example extends DoesThings {
      val system = ActorSystem("example")
      val ref = findActor
    }
    

    哈克快乐!

    【讨论】:

      【解决方案2】:

      您可以在 trait 中放置一个 actor 系统 val。

      通过实例化,您可以将使用过的演员系统传递给它。

      【讨论】:

        【解决方案3】:

        你可以试试这样的:

        trait ActorLookup{
          def actorSelection(path:ActorPath)(implicit fact:ActorRefFactory) = fact.actorSelection(path)
        
          def actorSelection(path:String)(implicit fact:ActorRefFactory) = fact.actorSelection(path)
        }
        
        class ActorBasedImpl extends Actor with ActorLookup{
        
          def receive = {
            case _ =>
              val ref = actorSelection("/foo")
          }
        }
        
        class NonActorBasedImpl extends ActorLookup{
          implicit val system = ActorSystem("foo")
          ...
          val ref = actorSelection("/user/foo")
        }
        

        在一个 Actor 中,您已经有一个隐含的 ActorRefFactory 在范围内,因此无需定义一个。如果您想在此处使用 ActorSystem,则可以像这样显式传递它:

        actorSelection("/user/foo")(context.system)
        

        在 Actor 之外,您更有可能使用 ActorSystem 而不是 ActorContext 来执行查找,因此这就是定义隐式 ActorSystem 的原因。但同样,您不必将其定义为隐式,如果需要,可以显式使用它。

        【讨论】:

        • 谢谢,我今天试试!
        猜你喜欢
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        • 1970-01-01
        • 2020-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多