《scala 深入浅出实战》 王家林
akka 入门之用akka实现一个word计数程序
环境
架构
这里只列出关键类的源码,整个项目的源代码参见:https://github.com/pengyucheng相关目录
MapReduceApplication源码
package akka.dt.app.scala.messages import akka.actor.{ActorSystem, Props} import akka.dt.app.scala.actors.MasterActor /** * Created by pengyucheng on 16-4-12. */ object MapReduceApplication { def main(args: Array[String]) { val _system = ActorSystem("HelloAkka") val master = _system.actorOf(Props[MasterActor],name = "master") println(master.path) master ! "Hi, this is ivy , more information at pengych cool" master ! "you are my sunshine my only sunshine ,please do remember what you want from me !" master ! "one life , more more at pengych live it !" Thread.sleep(5000) master ! new Result Thread.sleep(5000) _system.terminate() } }
package akka.dt.app.scala.actors import akka.actor.{Actor, ActorRef, Props} import akka.dt.app.scala.messages.Result /** * Created by pengyucheng on 16-4-12. */ class MasterActor extends Actor{ val aggregateActor:ActorRef = context.actorOf(Props[AggregateActor],name = "aggregate") val reduceActor:ActorRef = context.actorOf(Props(new ReduceActor(aggregateActor)),name = "reduce") val mapActor:ActorRef = context.actorOf(Props(new MapActor(reduceActor)),name = "map") def receive:Receive = { case message:String => mapActor ! message case message:Result => aggregateActor ! message case _ => } }AggregateActor源码
package akka.dt.app.scala.actors import akka.actor.Actor import akka.dt.app.scala.messages.{ReduceData, Result} import scala.collection.JavaConversions._ /** * Created by pengyucheng on 16-4-12. */ class AggregateActor extends Actor { var finalReducedMap = new java.util.HashMap[String,Integer] def receive:Receive = { case message:ReduceData => aggregateInMemoryReduce(message.reduceData) case message:Result => System.out.println(finalReducedMap.toString) } def aggregateInMemoryReduce(reducedList:java.util.HashMap[String,Integer]) = { var count:Integer = 0 for (key <- reducedList.keySet()){ if(finalReducedMap.containsKey(key)){ count = reducedList.get(key) count += finalReducedMap.get(key) finalReducedMap.put(key,count) } else { finalReducedMap.put(key,reducedList.get(key)) } } } }
akka://HelloAkka/user/master
{,please=1, sunshine=2, hi,=1, do=1, life=1, remember=1, are=1, only=1, me=1, from=1, you=2, live=1, !=2, pengych=2, more=3, cool=1, want=1, one=1, this=1, it=1, ,=2, my=2, ivy=1, at=2, what=1, information=1}
Process finished with exit code 0
一、word-count源码分析
二、akka 源码分析