有没有一种方法可以在ActorSystem中将值从actor发送到actorRef

时间:2018-11-15 16:09:31

标签: scala akka

我有两个演员,编码如下。

class Actor1 extends Actor {
    val r : ActorRef = actorOf (Props[Actor2], "master")

    def receive: Receive = {
        case class Mul (a,b) =>
            r ! CalcMul (a,b)

        case class MulReply (ans) =>
            println("Multiply result : " + ans)
            // want to send "ans" value to testObject..
    }
}

class Actor2 extends Actor {

    def receive: Receive = {
        case class CalcMul (a,b) =>
            sender ! MulReply (a*b)
    }
}

object testObject extends App {
    val a = ActorSystem("ActorSystem").actorOf(Props[Actor1], "root")

    a ! CalcMul (5, 15)
    // how to receive "ans" value here?
}

我能够在Actor1中接收和打印结果,但需要在testObject中使用这些值,以便将来将其用于以后的操作。无法在receive中使用testObject方法来接收来自Actor1的{​​{1}}中的消息,因此无法使用Actor2方法发送消息。

1 个答案:

答案 0 :(得分:1)

当您希望收到演员的回应时,可以为此使用问号模式。

import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.pattern._
import akka.util.Timeout

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.concurrent.duration.SECONDS


case class CalsMul(a: Int, b: Int)

  class Actor1 extends Actor {
    val r: ActorRef = context.actorOf(Props[Actor2], "master")

    def receive: Receive = {
      case req: CalsMul =>
        println("received message by Actor1")
        r forward req
    }
  }

  class Actor2 extends Actor {

    def receive: Receive = {
      case request: CalsMul =>
        println("received message by Actor2")
        Future.successful(request.a * request.b) pipeTo sender
    }
  }

  object testObject extends App {
    implicit val system: ActorSystem = ActorSystem("ActorSystem")
    val a: ActorRef = system.actorOf(Props[Actor1], "root")
    implicit val timeout: Timeout = Timeout(20, SECONDS)

    println(system, "sending message to Actor1")
    val ans: Future[Int] = (a ? CalsMul(5, 15)).mapTo[Int] // as you are returning the multiplication of a*b

    ans.foreach(println)
  }

注意:不建议将CPU绑定操作与actor一起使用,因为它会对应用程序的性能产生不利影响