Scala akka类型:如何从其实例获取ActorRef到Actor并发送消息本身?

问题描述 投票:1回答:1

我想从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中的实例保存为var myActorRef到Actor。然后我用myActorRef通过SendMyself消息将Actor实例的消息发送给自身。

但是,正如您所看到的,我正在使用变量,这不好:要保存ActorRef,需要将myActorRef类实例的字段MyActorInstancenull重写为ActorRef-仅对var iables是可能的。

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

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

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

scala reference akka actor self
1个回答
0
投票

没有必要进行如此复杂的舞蹈,只需使用ctx.self。在问之前,请至少阅读最基本的文档,它甚至可以节省您的时间。

© www.soinside.com 2019 - 2024. All rights reserved.