Is there a way to send values from actor to actorR

2019-08-16 16:21发布

问题:

I have two actors coded as follows.

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?
}

I am able to receive and print the result in Actor1 but need those values in testObject so I can use them for future operations. Cannot have a receive method in testObject as done to receive a message in Actor1 from Actor2, so cannot send them with tell method.

回答1:

As you want to receive a response from an actor you can use ask pattern for this purpose.

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)
  }

Note: CPU bound operations are not advised to use with actors it can have adverse effect on the performance of your application



标签: scala akka