Akka笔记(一)
class First extends Actor { val log = Logging(context.system,this) def receive = { case "test" => log.info("hello,test") case _ => log.info("other") }}object First extends App{ val system = ActorSystem("first") val f = system.actorOf(Props[First],"f"); f ! "test" system.shutdown}
?
Akka实现Receive函数,必须穷尽所有消息,否则akka.actor.UnhandledMessage(message, sender, recipient)
?将发送至ActorSystem‘s EventStream???
?
第二个例子
class Second extends Actor{ val first = context.actorOf(Props[First],"f2"); val log = Logging(context.system,this) def receive = { case "test" => log.info("hello,test") case _ => log.info("other") }}?Actor是一个树层结构,system创建的Actor为顶层Actor,Actor里头只能用context进行创建,创建的对象为这个Actor的子Actor。父Actor负责子Actor创建,发送消息,关闭等。
?
Actor生命周期
Actor有四个回调函数:
?
def preStart() {}def preRestart(reason: Throwable, message: Option[Any]) { context.children foreach (context.stop(_))postStop() }def postRestart(reason: Throwable) { preStart() }def postStop() {}1. Actor在初始化的时候,调用preStart这个函数是初始化工作处理的最佳阶段。?
2.重启,当Actor在处理消息时,抛出异常,这时候会调用重启过程。
旧的Actor的preRestart将会被掉用,默认实现关闭掉所有的子Actor,调用postStop()新的Actor被创建,postReStart将首先被调用,同时默认的初始化调用preStart3.stop方法postop将会被调用。?