标签:akka
关于什么是Akka本文就不再细说了,可见以下文章:
本文采用一个“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; } }
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()); }
然后创建连个Actory:player1,player2;
然后初始化他们的名字为P1,P2 ;
然后P1开球, 进入回合。
标签:akka
原文地址:http://blog.csdn.net/jmppok/article/details/44938047