akka 入门例子
来自akka官方文档。
import akka.actor._ import akka.routing.RoundRobinRouter import akka.util._ import scala.concurrent.duration._ object Pi extends App { def caculate (nrOfWorks:Int, nrOfMessage:Int, nrOfElement:Int){ val system = ActorSystem("PiSystem") val listener = system.actorOf(Props[Listener], name="listener") val master = system.actorOf(Props(new Master(nrOfWorks,nrOfMessage,nrOfElement,listener)), name="master") master ! Caculate } caculate (4, 10000, 10000) } sealed trait PiMessager case object Caculate extends PiMessager case class Work(start:Int, nrOfElements:Int) extends PiMessager case class Result(value:Double) extends PiMessager case class PiApproxomation(pi:Double, duration:Duration) class Worker extends Actor{ def receive = { case Work(start,nrOfElements) => sender ! Result(calculatePiFor(start, nrOfElements)) } def calculatePiFor(start:Int, nrOfElements:Int):Double ={ var acc = 0.0 for(i <- start until (start + nrOfElements)){ acc += 4.0 * (1- (i%2)*2)/(2*i+1) } acc } } class Master (nrOfWorks:Int, nrOfMessage:Int, nrOfElement:Int, listener:ActorRef) extends Actor { var pi: Double = _ var nrOfResults: Int = _ val start: Long = System.currentTimeMillis() val workerRouter = context.actorOf( Props[Worker].withRouter(RoundRobinRouter(nrOfWorks)), name = "workerRouter" ) def receive = { case Caculate => { for (i <- 0 until nrOfMessage) workerRouter ! Work(i*nrOfElement, nrOfElement) } case Result(value) => { pi += value nrOfResults +=1 if(nrOfResults == nrOfMessage){ listener ! PiApproxomation(pi, (System.currentTimeMillis()-start).millis) context.stop(self) } } } } class Listener extends Actor{ def receive = { case PiApproxomation(pi:Double, duration:Duration) => { println("\n\tPi approximation: \t\t%s\n\tCalculation time: \t%s".format(pi, duration)) context.system.shutdown() } } }
流程图: