【问题标题】:Scala akka typed: how to get ActorRef to Actor from it's instance and send message itself?Scala akka 键入:如何从它的实例中获取 ActorRef 到 Actor 并自己发送消息?
【发布时间】:2020-06-26 09:30:29
【问题描述】:

我想从 Actor 实例(从它的行为创建的案例类/类)向它的 Actor 发送消息。

我通过保存实例获得它,然后在其中保存ActorRef

val (instance, behaviour) = MyActorInstance(Nothing)
val actor = ActorSystem(instance, "SomeName123")
//save it here
instance.setMyActor(actor)

object MyActorInstance {
  def apply(ctx: ActorContext[Commands]): (MyActorInstance,Behavior[Commands]) = {
    val actorInstance = new MyActorInstance(ctx)
    val behaviour: Behavior[Commands] =
      Behaviors.setup { context =>
        {
          Behaviors.receiveMessage { msg =>
            actorInstance.onMessage(msg)
          }
        }
      }
    (actorInstance,behaviour)
  }
}

class MyActorInstance(context: ActorContext[Commands]) extends AbstractBehavior[Commands](context) {

  protected var myActorRef: ActorRef[Commands] = null

  def setMyActor(actorRef: ActorRef[Commands]): Unit = {
    myActorRef = actorRef
  }

  override def onMessage(msg: Commands): Behavior[Commands] = {
    msg match {
      case SendMyself(msg) =>
        myActorRef ! IAmDone(msg)
        Behaviors.same
      case IAmDone(msg) =>
        println(s"Send $msg to myself!")
        Behaviors.same
    }
  }
}

这里我将ActorRef 保存到Actor 中,因为它是var myActorRef 中的实例。 然后我使用 myActorRef 通过 SendMyself 消息从 Actor 的实例向自身发送消息。

但是为此,如您所见,我正在使用变量,这并不好:要保存 ActorRef,需要将 MyActorInstance 类实例的字段 myActorRefnull 重写为 ActorRef -只有 variables 才有可能。

如果我尝试使用 val 并通过将实例重写为新实例来创建不可变类,然后将其从旧实例交换为新实例,我的 Actor actor 仍然链接到 myActorRef == null 的旧实例。

现在我找到了一种方法:只使用var 而不是val 或不可变类。

但我想使用 val 或什么都不用。 为此,我需要从它的实例中获取 ActorRef,但是如何?

【问题讨论】:

    标签: scala reference akka actor self


    【解决方案1】:

    没有理由这么复杂的舞蹈,就用ctx.self吧。并且请在询问之前至少阅读最基本的文档,它甚至可以节省您的时间。

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多