Akka Learning to realize workcount
Package com.dcx.scala.actorimport akka.actor. {Actor, ActorRef, ActorSystem, Props} import scala.collection.mutable.HashMapimport scala.collection.mutable.ListBufferimport scala.io.Source/** * ideas: * to have a Server * to have a Client to communicate, client to count the text and then output (qy,3) to Server Server then aggregates all the qy into ListBuffer * / object AkkaWordCount {/ / variable length List val list = new ListBuffer [HashMap [String,Int]] def main (args: Array [String]): Unit = {/ / enter data text val files: Array [String] = Array ("D:\ tmp\\ input\\ word3.txt", "D:\ tmp\\ input\\ word3.txt" "D:\\ tmp\\ input\\ word3.txt") / / Storage the result data processed by each actor received / / store the Future data returned by actor / / take ActorSystem is a static factory val weChatApp = ActorSystem ("WeChatApp") / / get the correspondence address of two Actor val akkaServerRef: ActorRef = weChatApp.actorOf (Props [AkkaServer], "jianjian1") val clientRef: ActorRef = weChatApp.actorOf (Props (new Client (akkaServerRef)) "jianjian") for (file {/ map stage / / val list: List [String] = Source.fromFile (filePath). GetLines (). ToList// val words: List [String] = list.flatMap (_ .split (")) / / val res: Map [String, Int] = words.map ((_ 1). GroupBy (_. _ 1). MapValues (_ .size) / / asynchronously send the result data res to Server, go to pattern matching / / serverRef! Res//} case filePath:String = > {val list: List [String] = Source.fromFile (filePath). GetLines (). ToList val words: List [String] = list.flatMap (_ .split (")) / / (qy,3) format val res: Map [String, Int] = words.map ((_, 1). GroupBy (_. _ 1). MapValues (_ .size) serverRef! Res} import scala.collection.mutable.HashMapclass AkkaServer extends Actor {private var hashMap: HashMap [String,Int] = new HashMap [String,Int] override def receive: Receive = {case context: Map [String,Int] = > {/ / (qy,3) context.map ((map: (String,Int)) = > {/ / aggregate val value: Any = hashMap.getOrElse (map._1) None) if (value! = None) {hashMap (map._1) = value.asInstanceOf [Int] + map._2} else {hashMap (map._1) = map._2}}) AkkaWordCount.list + = hashMap}