演员无法识别消息

时间:2014-08-12 13:50:30

标签: scala akka

我想更加熟悉akka。目前,我正在以非常简单的方式发送消息(下一步是发送ActorRef)。但是当我尝试使用消息发送数据时,我的目标actor无法识别它。

这是我写的代码:

import akka.actor.Actor
import akka.actor.Props
import akka.pattern.gracefulStop
import scala.concurrent.duration._
import akka.util._
import scala.concurrent._
import java.util.concurrent._
import scala.Array._
import akka.actor.ScalaActorRef//for ActorRef
import scala.concurrent.ExecutionContext.Implicits.global

sealed trait MSG
case class msgTest(
    content: Int
) extends MSG

class a extends Actor {
    def receive = {
        case "start" =>
            println("emit")
        case _      =>
            println("wut?")
        case msgTest(content) =>
            println("content: ?")
    }
}

object main extends App {
    val system = akka.actor.ActorSystem("mySystem")
    val a = system.actorOf(Props[a], name = "a")

    a ! "start"
    a ! msgTest(80085)
    a ! "start"
}

这是我的输出:

[success] Total time: 6 s, completed Aug 12, 2014 3:39:35 PM
> run
[info] Running main 
emit
wut?
emit

1 个答案:

答案 0 :(得分:2)

订单在param匹配中很重要,您的默认匹配在您发送的actor消息之前出现:

def receive = {
    case "start" =>
        println("emit")
    case _      => // <-- here
        println("wut?")
    case msgTest(content) =>
        println("content: ?")
}

应该是:

def receive = {
    case "start" =>
        println("emit")
    case msgTest(content) =>
        println("content: ?")
    case _      => // <-- now execute only when every other match fails
        println("wut?")
}

在第一种情况下,当您发送msgTest时,第二次匹配是成功的,因为_是一个全部捕获,您很可能总是希望将捕获全部保留在最后。