Akka actor的方法调用接收方法未处理传递的消息

时间:2018-08-29 16:39:10

标签: scala akka actor

在下面的简化代码片段中,如果将接收功能重构了,那么它将无法按预期处理传入的消息。

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

我原本希望输出中也低于该行,但是不知何故,它不会来。

  

收到的味精是“你好”

1 个答案:

答案 0 :(得分:1)

问题:

handleMsg返回名为Receive的部分函数,​​但不对其求值。那就是为什么没有显示输出

  1. 对演员的行为使用context.become

  1. 使handleMsg函数返回单位,而不是未赋值的Partial函数

如下定义您的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")
  }

您可以使用成为

case msg => {
  debug("now calling handle")
  context become handleMsg
  self ! msg
}