Scala中Akka演员的调用方法 [英] call methods on akka actors in scala

查看:73
本文介绍了Scala中Akka演员的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个演员定义为:

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 to actorOf or actorFor
  • 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:

  • Create the ref to ActorB in the ActorA's initialization code as shown in http://doc.akka.io/docs/akka/2.0.3/scala/actors.html
  • Send the ActorB's reference to the ActorA as a specific message. Then ActorA can store the reference within receive 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆