我想从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
类实例的字段MyActorInstance
从null
重写为ActorRef
-仅对var iables是可能的。
[如果我尝试使用val并通过为新实例重写其实例来创建不可变类,然后将其从旧实例交换为新实例,则我的Actor actor
仍链接到旧实例myActorRef == null
。
现在我找到了一种方法:仅使用var
而不是val
或不可变的类。
但是我不想使用val或什么都不用。为此,我需要从其实例中获取ActorRef,但是如何?
没有必要进行如此复杂的舞蹈,只需使用ctx.self
。在问之前,请至少阅读最基本的文档,它甚至可以节省您的时间。