我有一个演员创造了另一个演员:
class MyActor1 extends Actor {
val a2 = system actorOf Props(new MyActor(123))
}
第二个参与者在创建后必须初始化(引导)自身,并且只有在此之后它才必须能够执行其他工作。
class MyActor2(a: Int) extends Actor {
//initialized (bootstrapped) itself, potentially a long operation
//how?
val initValue = // get from a server
//handle incoming messages
def receive = {
case "job1" => // do some job but after it's initialized (bootstrapped) itself
}
}
所以第一件事MyActor2
必须做的就是进行一些初始化工作。由于是向服务器发出请求,因此可能需要一些时间。只有在成功完成后,它才必须能够通过以下方式处理传入消息receive
。在此之前 - 它绝对不能这样做。
当然,对服务器的请求必须是异步的(最好使用Future
, not async
, await
或其他高级的东西,比如AsyncHttpClient
)。我知道如何使用 Future,但这不是问题。
我如何确保这一点?
p.s.我的猜测是它必须首先向自己发送一条消息。
你可以使用become
初始化后改变 actor 行为的方法:
class MyActor2(a: Int) extends Actor {
server ! GetInitializationData
def initialize(d: InitializationData) = ???
//handle incoming messages
val initialized: Receive = {
case "job1" => // do some job but after it's initialized (bootstrapped) itself
}
def receive = {
case d @ InitializationData =>
initialize(d)
context become initialized
}
}
请注意,此类参与者将在初始化之前删除所有消息。您必须手动保留这些消息,例如使用Stash:
class MyActor2(a: Int) extends Actor with Stash {
...
def receive = {
case d @ InitializationData =>
initialize(d)
unstashAll()
context become initialized
case _ => stash()
}
}
如果你不想使用var
对于初始化,您可以使用创建初始化行为InitializationData
像这样:
class MyActor2(a: Int) extends Actor {
server ! GetInitializationData
//handle incoming messages
def initialized(intValue: Int, strValue: String): Receive = {
case "job1" => // use `intValue` and `strValue` here
}
def receive = {
case InitializationData(intValue, strValue) =>
context become initialized(intValue, strValue)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)