来自 Akka actor 的方法调用接收方法不处理传递的消息
method call from Akka actor receive method is not handling passed message
在下面的简化代码片段中,如果 receive 的功能被重构,那么它不会按预期处理传入的消息。
package spack
import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.scalalogging.LazyLogging
object Main extends LazyLogging {
import logger._
def main(args: Array[String]): Unit = {
debug("start of main")
val system = ActorSystem("SampleSystem")
val ref = system.actorOf(Props[SampleActor])
ref ! "Hello"
debug("end of main")
Thread.sleep(Integer.MAX_VALUE)
}
}
class SampleActor extends Actor with LazyLogging {
import logger._
override def receive: Receive = {
case msg => {
debug("now calling handle")
handleMsg(msg)
}
}
def handleMsg(msg1: Any): Receive = {
case msg1 => debug(s"received msg is $msg1")
}
}
以上代码片段的输出:-
22:06:17.889 [main] DEBUG spack.Main$ - start of main
22:06:18.569 [main] DEBUG spack.Main$ - end of main
22:06:18.569 [SampleSystem-akka.actor.default-dispatcher-5] DEBUG spack.SampleActor - now calling handle
我原以为输出中也有下面一行,但不知何故,它没有出现。
received msg is "Hello"
问题:
handleMsg
returns 是一个名为 Receive
但不对其求值的偏函数。这就是为什么没有显示输出的原因
- 对演员的行为使用
context.become
或
- 使
handleMsg
函数成为return单元,而不是未计算的偏函数
像下面这样定义你的handleMsg
def handleMsg(arg: Any): Unit = arg match {
case msg => debug(s"received msg is $msg")
}
或
def handleMsg: Receive = {
case msg1 => debug(s"received msg is $msg1")
}
你可以使用 become
case msg => {
debug("now calling handle")
context become handleMsg
self ! msg
}
在下面的简化代码片段中,如果 receive 的功能被重构,那么它不会按预期处理传入的消息。
package spack
import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.scalalogging.LazyLogging
object Main extends LazyLogging {
import logger._
def main(args: Array[String]): Unit = {
debug("start of main")
val system = ActorSystem("SampleSystem")
val ref = system.actorOf(Props[SampleActor])
ref ! "Hello"
debug("end of main")
Thread.sleep(Integer.MAX_VALUE)
}
}
class SampleActor extends Actor with LazyLogging {
import logger._
override def receive: Receive = {
case msg => {
debug("now calling handle")
handleMsg(msg)
}
}
def handleMsg(msg1: Any): Receive = {
case msg1 => debug(s"received msg is $msg1")
}
}
以上代码片段的输出:-
22:06:17.889 [main] DEBUG spack.Main$ - start of main
22:06:18.569 [main] DEBUG spack.Main$ - end of main
22:06:18.569 [SampleSystem-akka.actor.default-dispatcher-5] DEBUG spack.SampleActor - now calling handle
我原以为输出中也有下面一行,但不知何故,它没有出现。
received msg is "Hello"
问题:
handleMsg
returns 是一个名为 Receive
但不对其求值的偏函数。这就是为什么没有显示输出的原因
- 对演员的行为使用
context.become
或
- 使
handleMsg
函数成为return单元,而不是未计算的偏函数
像下面这样定义你的handleMsg
def handleMsg(arg: Any): Unit = arg match {
case msg => debug(s"received msg is $msg")
}
或
def handleMsg: Receive = {
case msg1 => debug(s"received msg is $msg1")
}
你可以使用 become
case msg => {
debug("now calling handle")
context become handleMsg
self ! msg
}