[英]Is there a way to send values from actor to actorRef in ActorSystem
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. 我可以在
Actor1
接收和打印结果,但需要在testObject
中使用这些值,以便将来将其用于操作。 Cannot have a receive
method in testObject
as done to receive a message in Actor1
from Actor2
, so cannot send them with tell
method. 在
testObject
中testObject
像在testObject
那样具有receive
方法来从Actor2
接收Actor1
的消息,因此无法使用tell
方法发送它们。
As you want to receive a response from an actor you can use ask pattern for this purpose. 当您希望收到演员的回应时,您可以使用Ask模式。
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 注意: 不建议将与CPU绑定的操作与actor一起使用,因为它会对应用程序的性能产生不利影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.