/akka的生命周期:
1prestart()–刚刚创建,用于初始化用
2preRestart()–重启时的回调
3postRestart()–重启完时调用
4postStop()–结束时调用
package akka;
import akka.actor.*;
import com.typesafe.config.ConfigFactory;
public class live {
public static class greeter extends UntypedActor{
public static enum msg{
WORK,DONE,CLOER,
}
@Override
public void preStart() throws Exception {
System.out.println("start working");
}
@Override
public void postStop() throws Exception {
System.out.println("stop work");
}
@Override
public void onReceive(Object o) throws Throwable {
if(o==msg.WORK){
System.out.println("im will begin work");
}else if(o==msg.DONE){
System.out.println("im will done");
}
else if(o==msg.CLOER){
System.out.println("i will shutdown");
getSender().tell(msg.CLOER,getSelf());
context().stop(getSelf());
}else{
unhandled(o);
}
}
}
public static class watcher extends UntypedActor{
public watcher(ActorRef ref){
getContext().watch(ref);
//此处用于监听ref的变化
}
@Override
public void onReceive(Object o) throws Throwable {
if(o==greeter.msg.DONE){
}
if(o instanceof Terminated){//如果ref结束了,就会发消息给监听者
System.out.println(String.format("%s has terminated ,shut down system",((Terminated)o).getActor().path()));
//此方法可以得到发消息的actor
getContext().system().shutdown();
}
}
}
public static void main(String[] args) {
ActorSystem system=ActorSystem.create("watch", ConfigFactory.load("akka.conf"));
ActorRef woke=system.actorOf(Props.create(greeter.class),"worker");
system.actorOf(Props.create(watcher.class,woke),"watcher");
woke.tell(greeter.msg.WORK,ActorRef.noSender());
woke.tell(greeter.msg.DONE,ActorRef.noSender());
woke.tell(PoisonPill.getInstance(),ActorRef.noSender());
}
}