Akka 2.1尝试的一个小例子

关于什么是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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值