• 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("
    	Pi approximation: 		%s
    	Calculation time: 	%s".format(pi, duration))
          context.system.shutdown()
        }
      }
    }
    



    流程图:





  • 相关阅读:
    AOP的实现原理——动态代理
    反射
    代理模式
    sprig——jar包
    spring事务管理
    [c++基础]3/5原则--拷贝构造函数+拷贝赋值操作符
    [c++面试准备]--vector对象是如何增长的
    c++面试须知
    redhat--1
    kvm配置虚拟机[待整理]
  • 原文地址:https://www.cnblogs.com/leeeee/p/7276107.html
Copyright © 2020-2023  润新知