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