Scala中Akka演员的调用方法 [英] call methods on akka actors in scala
问题描述
我有一个演员定义为:
class nodeActor(ID: String) extends Actor
其中包含一个方法,该方法用于在actor启动之前对其进行设置:
which contains a method, which is used to set up the actor before it is started:
def addRef(actor:ActorRef)
我实例化了这个actor:
I instantiate this actor as so:
val node1 = system.actorOf(Props(new nodeActor("node1")), name="node1")
,这会返回一个ActorRef。编译器不允许我在ActorRef上调用 addRef,因为它是该子类型的成员。因此,我使用以下方式投射节点:
which returns me an ActorRef. The compiler doesn't let me call "addRef" on an ActorRef since it's a member of the subtype. So I cast the node using:
node1.asInstanceOf[nodeActor].addRef(link1)
这使编译器感到满意。然后在运行时,我得到
Which keeps the compiler happy. Then at runtime I get
java.lang.ClassCastException: akka.actor.LocalActorRef cannot be cast to ActorStressTest.nodeActor
这对我来说似乎根本没有意义,因为它是子类型,我应该可以将其转换为它。
which doesn't even seem to make sense to me since it's a subtype and I should be able to cast to it.
想法?
推荐答案
您不应该打电话一个演员的方法直接来自另一个类。它破坏了整个系统的设计,即
You're not supposed to call an actor's methods directly from another class. It breaks the whole design of the system, which is
- 通过仅与
进行通信来封装参与者的特定实现。通过调用
actorOf
或actorFor
- 使用可用的(
!
,?
)方法将参与者之间的通信限制为消息传递
获得的ActorRef
- to encapsulate the actor's specific implementation by communicating only with the
ActorRef
obtained with the call toactorOf
oractorFor
- to limit communication between actors to message passing, using the available (
!
,?
) methods
如果需要在 ActorA
中创建对另一个的引用ActorB
您可以:
If you need to create a reference in ActorA
to another ActorB
you can:
- 创建对
ActorB
在ActorA
的初始化代码中,如 http://doc.akka.io/docs/akka/2.0.3/scala/actors.html - 发送
ActorB
引用ActorA
作为特定消息。然后ActorA
可以将引用存储在接收
实现中
- Create the ref to
ActorB
in theActorA
's initialization code as shown in http://doc.akka.io/docs/akka/2.0.3/scala/actors.html - Send the
ActorB
's reference to theActorA
as a specific message. ThenActorA
can store the reference withinreceive
implementation
如果需要调用方法来满足Interface / Trait约束,请查看打字演员
If you need to call a method to satisfy an Interface/Trait constraint, have a look at Typed Actors
这篇关于Scala中Akka演员的调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!