akka的優點太多,高效能、高可靠、高併發、分布式、可容錯、可擴充套件、事件驅動,不一一敘述。不同版本的api差異很大,本文**執行在 scala 2.10.3 和 akka 2.3.2 之上。
定義actor很簡單,繼承 akka.actor.actor ,實現receive方法即可。com.typesafe.akkagroupid>
akka-actor_2.10artifactid>
2.3.2version>
dependency>
org.scala-langgroupid>
scala-libraryartifactid>
2.10.3version>
dependency>
classhello
extends
actor
}
建立actor例項需要通過 actorsystem 。
val system = actorsystem("hellosystem")如果要在 actor 中繼續建立子 actor,需要使用內建的 actorcontext 物件。val hello = system.actorof(props[hello], name = "hello")
val hello1 = system.actorof(props[hello])
val hello2 = system.actorof(props(new hello()))
context.actorof(props[children], name = "children")如果要建立遠端 actor,需要通過 actorselection 方法,原 actorfor 方法不再使用。
context.actorselection("akka.tcp:")巨簡單,就是乙個!,可以傳送任意型別的訊息,此訊息是非同步的。
hello ! "bruce"同步訊息的傳送需要使用 future 物件。hello ! 10086
implicit val timeout = timeout(5 seconds)有兩種方式停止乙個actor。val future = hello ? "sha"
val result = await.result(future, timeout.duration).asinstanceof[string]
一種是通過內部 actorcontext.stop() 方法,該方法會將 children actor 逐層殺掉後,再自刎。
def receive =另一種是外部喂毒藥,通過 actorref.tell() 方法實現。後乙個引數是向誰reply,這裡顯然不需要,傳空。
hello.tell(poisonpill.getinstance, actorref.nosender);
哼哈二將本是兩位佛寺的門神俗稱,是執金剛神的一種。明代**《封神演義》作者陳仲琳據此附會兩員神將,形象威武兇猛。一名鄭倫,能鼻哼白氣制敵;一名陳奇,能口哈黃氣擒將。
objecthengha
extends
val system = actorsystem("henghasystem")
val ha = system.actorof(props[ha], name = "ha")
val heng = system.actorof(props(new heng(ha)), name = "heng")
heng ! "start"
}
classheng
(ha: actorref)
extends
actor
}
classrun 起來,結果:haextends
actor
}
哼哈哼哈哼...
akkaremote
}}
objectlocal
extends
val system = actorsystem("localsystem")
val localactor = system.actorof(props[localactor], name = "localactor") // the local actor
localactor ! "start"
// start the action
}
classlocalactor
extends
actor
}}
akkaremote
}}
objecthelloremote
extends
val system = actorsystem("helloremotesystem")
val remoteactor = system.actorof(props[remoteactor], name = "remoteactor")
remoteactor ! "the remoteactor is alive"
}
classremoteactor
extends
actor
}
Akka 快速入門
akka的優點太多,高效能 高可靠 高併發 分布式 可容錯 可擴充套件 事件驅動,不一一敘述。不同版本的api差異很大,本文 執行在 scala 2.10.3 和 akka 2.3.2 之上。com.typesafe.akkagroupid akka actor 2.10artifactid 2.3...
akka簡單入門例子
spark版本裡面用到的就是akka通訊,2.0版本 已經不再使用akka了。這裡寫了乙個簡單的akka程式。首先定義2個訊息類object myrequest object myresponse 定義2個通訊的actorclass student teacherref actorref exten...
AKKA 官方文件2 5 8 入門指南
到目前為止,akka 2.5.8版本 當前最新版本 官方文件的入門指南部分已經翻譯完了,第一節那個akka介紹有點無聊就沒翻,本人自感英語水平過差 其實語文也不咋地 所以看看英文文件提公升下詞彙量,然後就順手翻譯了下。為什麼現代系統需要乙個新的程式設計模型 actor模型如何滿足現代分布式系統的需求...