! 的源碼:
def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit
tell 的源碼:
final def tell(msg: Any, sender: ActorRef): Unit = this.!(msg)(sender)
forward 的源碼:
def forward(message: Any)(implicit context: ActorContext) = tell(message, context.sender())
通過源碼,我們可以輕而易舉的知道 :
! 發送的消息的發送者通過一個隐式轉換,把一個ActorRef轉換成sender,如果找不到ActorRef的話,那個發送者就是noSender。
forward 發送消息的發送者是目前消息的上一個發送者。
即:
A To B, B To C
如果通過!的方式發送消息,則C接收到的消息的發送者是B.
如果通過 forward 的方式發送消息,則C接收到的消息的發送者是A.
如果希望 !的方式發送消息的同時攜帶發送者消息,則可以使用 .!(msg)(sender)
如果希望關掉actor,直接shutdown或者使用父親actor的stop,在actor内部還可以使用context.stop(self)