关于甚么是Akka本文就不再细说了,可见以下文章:
散布式利用框架Akka快速入门
Storm Akka Finagle对照及使用处景分析
Akka 对照 Storm
本文彩用1个“Ping-Pong”(打乒乓球)的Demo进行尝试:
1.首先要定义两个Actor, 相互打。
2.然后要定义流程:初始化,1方发球,然后相互打回合。
3.还需要定义每一个消息的结构。
具体以下:
初始化消息 Init_MSG,初始化参赛者名称。
public static class Init_MSG {
public String name;
public Init_MSG(String name) {
this.name = name;
}
}
开始消息 Start_MSG, 包括1个属性,对手是谁(向谁发球)。
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());
}
首先创建1个ActorSystem;
然后创建连个Actory:player1,player2;
然后初始化他们的名字为P1,P2 ;
然后P1开球, 进入回合。