本节主要内容:
- Actor API解析
1. Actor API解析
Actor中的主要成员变量和方法定义如下:
package akka.actor
trait Actor extends scala.AnyRef {
type Receive = akka.actor.Actor.Receive
//context变量暴露当前Actor的上下文信息及当前消息
implicit val context : akka.actor.ActorContext = { /* compiled code */ }
//self作为当前ActorRef的引用
implicit final val self : akka.actor.ActorRef = { /* compiled code */ }
//当前Actor接收到最后一条消息对应的消息发送者(Actor)
final def sender() : akka.actor.ActorRef = { /* compiled code */ }
//receive方法,抽象方法,定义Actor的行为逻辑
def receive : akka.actor.Actor.Receive
//内部使用API
protected[akka] def aroundReceive(receive : akka.actor.Actor.Receive, msg : scala.Any) : scala.Unit = { /* compiled code */ }
protected[akka] def aroundPreStart() : scala.Unit = { /* compiled code */ }
protected[akka] def aroundPostStop() : scala.Unit = { /* compiled code */ }
protected[akka] def aroundPreRestart(reason : scala.Throwable, message : scala.Option[scala.Any]) : scala.Unit = { /* compiled code */ }
protected[akka] def aroundPostRestart(reason : scala.Throwable) : scala.Unit = { /* compiled code */ }
//监督策略,用于Actor容错处理
def supervisorStrategy : akka.actor.SupervisorStrategy = { /* compiled code */ }
//Hook方法,用于Actor生命周期监控
@scala.throws[T](classOf[scala.Exception])
def preStart() : scala.Unit = { /* compiled code */ }
@scala.throws[T](classOf[scala.Exception])
def postStop() : scala.Unit = { /* compiled code */ }
@scala.throws[T](classOf[scala.Exception])
def preRestart(reason : scala.Throwable, message : scala.Option[scala.Any]) : scala.Unit = { /* compiled code */ }
@scala.throws[T](classOf[scala.Exception])
def postRestart(reason : scala.Throwable) : scala.Unit = { /* compiled code */ }
//发送给Actor的消息,Actor没有定义相应的处理逻辑时,会调用此方法
def unhandled(message : scala.Any) : scala.Unit = { /* compiled code */ }
}
object Actor extends scala.AnyRef {
type Receive = scala.PartialFunction[scala.Any, scala.Unit]
//空的行为逻辑
@scala.SerialVersionUID(1)
object emptyBehavior extends scala.AnyRef with akka.actor.Actor.Receive {
def isDefinedAt(x : scala.Any) : scala.Boolean = { /* compiled code */ }
def apply(x : scala.Any) : scala.Nothing = { /* compiled code */ }
}
//Sender为null
@scala.SerialVersionUID(1)
final val noSender : akka.actor.ActorRef = { /* compiled code */ }
}
(1) Hook方法,preStart()、postStop()方法的使用
/*
*Actor API: Hook方法
*/
object Example_05 extends App{
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
class FirstActor extends Actor with ActorLogging{
//通过context.actorOf方法创建Actor
var child:ActorRef = _
//Hook方法,preStart(),Actor启动之前调用,用于完成初始化工作
override def preStart(): Unit ={
log.info("preStart() in FirstActor")
//通过context上下文创建Actor
child = context.actorOf(Props[MyActor], name = "myChild")
}
def receive = {