akka实战项目--1生命周期

/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());
       
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值