我有一个演员,它创建一个子演员来执行一些冗长的计算。
问题是子 Actor 的初始化需要几秒钟,并且父 Actor 在子 Actor 创建和完全初始化之间发送给子 Actor 的所有消息都将被丢弃。
这是我正在使用的代码的逻辑:
class ChildActor extends Actor {
val tagger = IntializeTagger(...) // this takes a few seconds to complete
def receive = {
case Tag(text) => sender ! tagger.tag(text)
case "hello" => println("Hello")
case _ => println("Unknown message")
}
}
class ParentActor extends Actor {
val child = context.ActorOf(Props[ChildActor], name = "childactor")
// the below two messages seem to get lost
child ! "hello"
child ! Tag("This is my sample text")
def receive = {
...
}
}
我怎样才能解决这个问题?是否可以让父 Actor 等到子 Actor 完全初始化?我将使用具有路由功能的子 Actor 并可能在远程 Actor 系统上使用。
EDIT
根据 drexin 的建议,我将代码更改为:
class ChildActor extends Actor {
var tagger: Tagger = _
override def preStart() = {
tagger = IntializeTagger(...) // this takes a few seconds to complete
}
def receive = {
case Tag(text) => sender ! tagger.tag(text)
case "hello" => println("Hello")
case _ => println("Unknown message")
}
}
class ParentActor extends Actor {
var child: ActorRef = _
override def preStart() = {
child = context.ActorOf(Props[ChildActor], name = "childactor")
// When I add
// Thread.sleep(5000)
// here messages are processed without problems
// wihout hardcoding the 5 seconds waiting
// the below two messages seem to get lost
child ! "hello"
child ! Tag("This is my sample text")
}
def receive = {
...
}
}
但问题仍然存在。我缺少什么?
不要初始化tagger
在构造函数中,但是在preStart
钩子,这样消息将被收集在消息框中,并在参与者准备好时传递。
edit:
你应该对你的演员创作做同样的事情ParentActor
类,因为你也会遇到同样的问题,如果ChildActor
会在之前做出回应ParentActor
已初始化。
edit2:
我创建了一个简单的示例,但无法重现您的问题。下面的代码工作得很好:
import akka.actor._
case class Tag(x: String)
class ChildActor extends Actor {
type Tagger = String => String
var tagger: Tagger = _
override def preStart() = {
tagger = (x: String) => x+"@tagged" // this takes a few seconds to complete
Thread.sleep(2000) // simulate time taken to initialize Tagger
}
def receive = {
case Tag(text) => sender ! tagger(text)
case "hello" => println("Hello")
case _ => println("Unknown message")
}
}
class ParentActor extends Actor {
var child: ActorRef = _
override def preStart() = {
child = context.actorOf(Props[ChildActor], name = "childactor")
// When I add
// Thread.sleep(5000)
// here messages are processed without problems
// wihout hardcoding the 5 seconds waiting
// the below two messages seem to get lost
child ! "hello"
child ! Tag("This is my sample text")
}
def receive = {
case x => println(x)
}
}
object Main extends App {
val system = ActorSystem("MySystem")
system.actorOf(Props[ParentActor])
}
输出是:
[info] Running Main
Hello
This is my sample text@tagged
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)