在遵循文档示例(2.1.4)之后,我在加载微内核的actor处理消息时遇到了麻烦,其中Bootable扩展类定义如下:
class HelloKernel extends Bootable {
val system = ActorSystem("hellokernel")
def startup = {
system.actorOf(Props[HelloActor]) ! Start
}
def shutdown = {
system.shutdown()
}
}
如果创建了一个虚拟实例(即没有在代码的其他任何地方使用),如下所示,那么消息将按照预期进行处理。
class HelloKernel extends Bootable {
val system = ActorSystem("hellokernel")
val dummyActor = system.actorOf(Props[HelloActor])
def startup = {
system.actorOf(Props[HelloActor]) ! Start
}
def shutdown = {
system.shutdown()
}
}
是否确实应该有一个虚拟实例化,或者,通过这样做,我是否引起了一些副作用,导致消息被处理?
基于Thomas Letschert在Akka 2.1最小远程actor示例中给出的代码,我已经将服务器端变成了一个微内核托管的actor。
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
import akka.kernel.Bootable
class Joe extends Actor {
def receive = {
case msg: String => println("joe received " + msg + " from " + sender)
case _ => println("Received unknown msg ")
}
}
class GreetServerKernel extends Bootable {
val system = ActorSystem("GreetingSystem")
val joe = system.actorOf(Props[Joe], name = "joe")
println(joe.path)
joe ! "local msg!"
println("Server ready")
def startup = {
}
def shutdown = {
println("PrimeWorker: Shutting Down")
system.shutdown
}
}
在这种情况下,虚拟实例化是
,当删除的消息不被处理时,它是 val joe = system.actorOf(Props[Joe], name = "joe")
呼叫方代码为
import akka.actor._
import akka.actor.ActorDSL._
object GreetSender extends App {
implicit val system = ActorSystem("GreetingSystem")
val joe = system.actorFor("akka://GreetingSystem@127.0.0.1:2554/user/joe")
println(joe.path)
val a = actor(new Act {
whenStarting { joe ! "Hello Joe from remote" }
})
joe ! "Hello"
println("Client has sent Hello to joe")
}
如果您发布的代码确实准确,那么只需将joe
实例的实例移动到startup
操作中,而不是在可引导类的构造函数中:
def startup = {
system.actorOf(Props[Joe], name = "joe")
}
绑定到名称joe
的actor需要在某人可以按名称查找它并向它发送消息之前启动。它基本上与在可引导类的构造函数中启动它相同,但我相信惯例规定在startup
函数中执行所有actor实例化,而不是可引导类主体(因此构造函数)