Akka之收件箱(Inbox)

我们已经知道,所有Actor之间的通信都是通过消息来进行的。我们不仅可以使用Actor对Actor进行消息的发送和接受,也可以使用收件箱组件对Actor进行消息的发送和接收, 使用收件箱大大的方便了应用程序与Actor之间的交互。

实例

package com.bzb.java8.akka;

import akka.actor.UntypedActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;

/**
 * @author bzb
 * @Description: 当前示例中的唯一一个Actor
 * @date 2018/9/14 14:16
 */
public class MyWorker extends UntypedActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);

    public static enum Msg {
        WORKING, DONE, CLOSE;
    }

    @Override
    public void onReceive(Object msg) throws Exception {
        if (msg == Msg.WORKING) {
            System.out.println("I am working");
        }
        if (msg == Msg.DONE) {
            System.out.println("Stop working");
        }
        if (msg == Msg.CLOSE) {
            System.out.println("I will shutdow");

            getSender().tell(Msg.CLOSE, getSelf());

            // 收到CLOSE消息时,关闭自己,结束运行。
            getContext().stop(getSelf());
        } else {
            unhandled(msg);
        }
    }
}
package com.bzb.java8.akka;

import akka.actor.*;
import com.typesafe.config.ConfigFactory;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;


/**
 * @author bzb
 * @Description:
 * @date 2018/9/14 16:41
 */
public class InBoxDemo {
    public static void main(String[] args) {

        // 在本例中,与MyWork交互的,并不是另外一个Actor,而是一个邮箱。
        ActorSystem system = ActorSystem.create("inboxdemo", ConfigFactory.load("sampehello.conf"));

        ActorRef worker = system.actorOf(Props.create(MyWorker.class), "worker");

        // 根据ActorSystem构造了一个与它绑定的邮箱
        Inbox inbox = Inbox.create(system);

        // 监视worker,当worker停止时,则会收到一条消息通知
        inbox.watch(worker);

        // 通过邮箱向worker发送消息
        inbox.send(worker, MyWorker.Msg.WORKING);
        inbox.send(worker, MyWorker.Msg.DONE);
        inbox.send(worker, MyWorker.Msg.CLOSE);

        while (true) {
            Object msg = inbox.receive(Duration.create(1, TimeUnit.SECONDS));
            if (msg == MyWorker.Msg.CLOSE) {
                System.out.println("MyWork is CLOSING");
            } else if (msg instanceof Terminated) { // 如果发现MyWork已停止工作,则关闭整个ActorSystem
                System.out.println("MyWork is dead");
                system.shutdown();
                break;
            } else {
                System.out.println(msg);
            }
        }

    }
}

猜你喜欢

转载自blog.csdn.net/java852987/article/details/82705730