class akka001 extends Actor{ override def preStart() ={ println("this is preStart()") } def receive = LoggingReceive{ case "hello" => println("hello world") } override def postStop()={ println("this is postStop()") } }
然后定义一个主类,给这个类的对象发送消息
/** * Created by hyj on 17-7-3. */ object AkkaMain { def main(args: Array[String]): Unit = { val actorSystem=ActorSystem("actorSystem") val lifecycleActor=actorSystem.actorOf(Props[cn.qzt360.akka.akka001],"testactor") lifecycleActor!"hello" actorSystem.shutdown() } }输出结果如下:
this is preStart() hello world this is postStop()
Akka的生命周期:会首先执行prestart方法,然后执行receive方法,用来处理消息,最后调用actorSystem.shutdown()的时候会触发postStop方法的执行