Akka 2.1嘗試的一個小例子
來源:程序員人生 發(fā)布時間:2015-04-27 08:23:06 閱讀次數(shù):3823次
關于甚么是Akka本文就不再細說了,可見以下文章:
散布式利用框架Akka快速入門
Storm Akka Finagle對照及使用處景分析
Akka 對照 Storm
本文彩用1個“Ping-Pong”(打乒乓球)的Demo進行嘗試:
1.首先要定義兩個Actor, 相互打。
2.然后要定義流程:初始化,1方發(fā)球,然后相互打回合。
3.還需要定義每一個消息的結構。
具體以下:
初始化消息 Init_MSG,初始化參賽者名稱。
public static class Init_MSG {
public String name;
public Init_MSG(String name) {
this.name = name;
}
}
開始消息 Start_MSG, 包括1個屬性,對手是誰(向誰發(fā)球)。
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實現(xiàn)(參賽者),根據(jù)消息類型進行相應的處理。
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());
}
首先創(chuàng)建1個ActorSystem;
然后創(chuàng)建連個Actory:player1,player2;
然后初始化他們的名字為P1,P2 ;
然后P1開球, 進入回合。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈