告诉和转发之间有什么区别,以防我发送相同的消息:
case msg: Message =>
otherActor tell (msg,sender)
和
case msg: Message =>
otherActor forward msg
答案 0 :(得分:101)
sender()
在接收端会有所不同。
邮件使用告诉(也称为!
)发送:
A
告知消息M
至B
。
B
告知该邮件发送给C
。
C
认为邮件sender()
的{{1}}为M
。
邮件使用转发:
B
告知消息A
至M
。
B
转发该邮件至B
C
认为邮件C
的{{1}}为sender()
。
值得指出的是,当使用M
明确设置邮件的发件人时,您可以达到与A
相同的效果,但这不是典型的Akka风格:
forward
有关详细信息,请参阅docs about forward。
答案 1 :(得分:15)
Tell将发件人设置为发送邮件的角色。
转发会保留邮件的原始发件人。
答案 2 :(得分:1)
target.tell(message,getSelf()); final Object result ="&#34 ;; target.forward(result,getContext());
下面, getself()是演员的自我引用。 getcontext()是主管参考。
答案 3 :(得分:0)
import akka.actor.{Actor, ActorSystem, Props}
case object FromActor3
/**
* forward method: Forwards the message and passes the original sender actor as the sender.
*/
object ActorForward extends App {
class ActorExample extends Actor {
def receive = {
case message: String =>
println(s"Message received from ${sender.path.name}, message = $message")
val child = context.actorOf(Props[Actor2], "ChildActor")
child ! message
case FromActor3 => println("Response when forwarded by Actor2 to Actor3")
}
}
class Actor2 extends Actor {
def receive = {
case message: String =>
println(s"Message received from ${sender.path.name}, message = $message")
val child = context.actorOf(Props[Actor3], "ChildActor")
println("forwarding...")
child forward message
case _ => println("Unknown message")
}
}
class Actor3 extends Actor {
def receive = {
case message: String =>
println(s"Message received from ${sender.path.name}, message = $message")
sender ! FromActor3
case _ => println("Unknown message")
}
}
val actorSystem = ActorSystem("ActorSystem")
val actor = actorSystem.actorOf(Props[ActorExample], "RootActor")
actor ! "Hello"
}