Akka 2.1尝试的一个小例子

来源:互联网 发布:常用mysql语句大全 编辑:程序博客网 时间:2024/05/19 06:18

关于什么是Akka本文就不再细说了,可见以下文章:

分布式应用框架Akka快速入门

Storm Akka Finagle对比及使用场景分析

Akka 对比 Storm 

本文采用一个“Ping-Pong”(打乒乓球)的Demo进行尝试:

1.首先要定义两个Actor, 相互打。

2.然后要定义流程:初始化,一方发球,然后相互打回合。

3.还需要定义每个消息的结构。

具体如下:

初始化消息 Init_MSG,初始化参赛者名称。

    public static class Init_MSG {        public String name;        public Init_MSG(String name) {            this.name = name;        }    }


开始消息 Start_MSG, 包含一个属性,对手是谁(向谁发球)。

    public static class Start_MSG {        public String opponent;        public Start_MSG(String opponentPath) {            opponent = opponentPath;        }    }

球打过来的消息  Ping

    public static class Ping {        public String from;        public Ping(String name) {            from = name;        }    }

Actor实现(参赛者),根据消息类型进行相应的处理。

    public static class Player extends UntypedActor {        private String name;        @Override        public void onReceive(Object arg0) throws Exception {            if (arg0 instanceof Init_MSG) {                this.name = ((Init_MSG) arg0).name;            }            if (arg0 instanceof Start_MSG) {                System.out.println("Start :" + name);                ActorRef opponent = getContext().actorSelection(((Start_MSG) arg0).opponent)                        .anchor();                opponent.tell(new Ping(name), getSelf());            } else if (arg0 instanceof Ping) {                System.out.println("From :" + ((Ping) arg0).from);                getSender().tell(new Ping(name), getSelf());            } else {                unhandled(arg0);            }        }    }

测试:

    public static void main(String[] args) {        // Create the 'ping-pong' actor system        final ActorSystem system = ActorSystem.create("ping-pong");        // Create the 'player1' actor        final ActorRef player1 = system.actorOf(Props.create(Player.class));        // Create the 'player2' actor        final ActorRef player2 = system.actorOf(Props.create(Player.class));        player1.tell(new Init_MSG("P1"), ActorRef.noSender());        player2.tell(new Init_MSG("P2"), ActorRef.noSender());        // player1 start        player1.tell(new Start_MSG(player2.path().toSerializationFormat()), ActorRef.noSender());    }

首先创建一个ActorSystem;

然后创建连个Actory:player1,player2;

然后初始化他们的名字为P1,P2 ;

然后P1开球, 进入回合。

1 0