Started to climb the Akka mountain

来源:互联网 发布:雅思考试推荐用书 知乎 编辑:程序博客网 时间:2024/06/05 13:21
-- Prerequisites

This tutorial assumes that you have Java 1.6 or later installed on you machine and java on your PATH.

You need to make sure that $JAVA_HOME environment variable is set to the root of the Java distribution. You also need to make sure that the $JAVA_HOME/bin is on your PATH:
$ export JAVA_HOME=/usr/lib/jvm/java-6-openjdk$ export PATH=$PATH:$JAVA_HOME/bin

You can test your installation by invoking java:
$ java -versionjava version "1.6.0_20"OpenJDK Runtime Environment (IcedTea6 1.9.9) (6b20-1.9.9-0ubuntu1~10.04.2)OpenJDK Server VM (build 19.0-b09, mixed mode)

-- Downloading and installing Scala

ou also need to make sure that the scala-2.9.0/bin (if that is the directory where you installed Scala) is on your PATH:

$ export PATH=$PATH:scala-2.9.0/bin
You can test your installation by invoking scala:

$ scala -versionScala code runner version 2.9.0.final -- Copyright 2002-2011, LAMP/EPFL

-- Downloading and installing Akka

step1: Akka Microkernel (all modules): akka-microkernel-1.1.3.zip (http://akka.io/downloads/akka-microkernel-1.1.3.zip)

step2: Once you have downloaded the distribution unzip it in the folder you would like to have Akka installed in. In my 
case I choose to install it in /home/shawny/software/akka-microkernel-1.1.3, simply by unzipping it to this directory.

step3: set the AKKA_HOME environment variable to the root of the distribution.
$ cd /home/shawny/software/akka-microkernel-1.1.3$ export AKKA_HOME=`pwd`$ echo $AKKA_HOME/home/shawny/software/akka-microkernel-1.1.3

The distribution looks like this:
$ ls -1configdoclibsrc

In the config directory we have the Akka conf files.
In the doc directory we have the documentation, API, doc JARs, and also the source files for the tutorials.
In the lib directory we have the Scala and Akka JARs.
In the src directory we have the source JARs for Akka.

-- Downloading and installing SBT

SBT, short for ‘Simple Build Tool’ is an excellent build system written in Scala.

Ref: https://github.com/harrah/xsbt

-- Creating an Akka SBT project

You do that by stepping into the directory you want to create your project in and invoking the sbt command answering the questions for setting up your project (just pressing ENTER will choose the default in square brackets):

Directory e.g: /home/shawny/workspace/scala/test

$ sbtProject does not exist, create new project? (y/N/s) yName: Tutorial 1Organization: Hakkers IncVersion [1.0]:Scala version [2.9.0-1]:sbt version [0.7.6.RC0]:

-- Copy jar files from home/shawny/software/akka-microkernel-1.1.3/lib to current project lib

shawny@ubuntu:~/workspace/scala/test/lib$ cp /home/shawny/software/akka-microkernel-1.1.3/lib/*.jar .shawny@ubuntu:~/workspace/scala/test/lib$ cp /home/shawny/software/akka-microkernel-1.1.3/lib/akka/*.jar .


-- Create scala file "Pi.scala" in /home/shawny/workspace/scala/test/src/main/scala

package akka.tutorial.first.scalaimport akka.actor.{Actor, PoisonPill}import Actor._import akka.routing.{Routing, CyclicIterator}import Routing._import java.util.concurrent.CountDownLatchobject Pi extends App {  calculate(nrOfWorkers = 4, nrOfElements = 10000, nrOfMessages = 10000)  // ====================  // ===== Messages =====  // ====================  sealed trait PiMessage  case object Calculate extends PiMessage  case class Work(start: Int, nrOfElements: Int) extends PiMessage  case class Result(value: Double) extends PiMessage  // ==================  // ===== Worker =====  // ==================  class Worker extends Actor {    // define the work    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    }    def receive = {      case Work(start, nrOfElements) =>        self reply Result(calculatePiFor(start, nrOfElements)) // perform the work    }  }  // ==================  // ===== Master =====  // ==================  class Master(    nrOfWorkers: Int, nrOfMessages: Int, nrOfElements: Int, latch: CountDownLatch)    extends Actor {    var pi: Double = _    var nrOfResults: Int = _    var start: Long = _    // create the workers    val workers = Vector.fill(nrOfWorkers)(actorOf[Worker].start())    // wrap them with a load-balancing router    val router = Routing.loadBalancerActor(CyclicIterator(workers)).start()    // message handler    def receive = {      case Calculate =>        // schedule work        //for (start <- 0 until nrOfMessages) router ! Work(start, nrOfElements)        for (i <- 0 until nrOfMessages) router ! Work(i * nrOfElements, nrOfElements)        // send a PoisonPill to all workers telling them to shut down themselves        router ! Broadcast(PoisonPill)        // send a PoisonPill to the router, telling him to shut himself down        router ! PoisonPill      case Result(value) =>        // handle result from the worker        pi += value        nrOfResults += 1        if (nrOfResults == nrOfMessages) self.stop()    }    override def preStart() {      start = System.currentTimeMillis    }    override def postStop() {      // tell the world that the calculation is complete      println(        "\n\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis"        .format(pi, (System.currentTimeMillis - start)))      latch.countDown()    }  }  // ==================  // ===== Run it =====  // ==================  def calculate(nrOfWorkers: Int, nrOfElements: Int, nrOfMessages: Int) {    // this latch is only plumbing to know when the calculation is completed    val latch = new CountDownLatch(1)    // create the master    val master = actorOf(      new Master(nrOfWorkers, nrOfMessages, nrOfElements, latch)).start()    // start the calculation    master ! Calculate    // wait for master to shut down    latch.await()  }}

-- Run it inside SBT

shawny@ubuntu:~/workspace/scala/test$ sbt[info] Building project scala object using sbt 1.0 against Scala 2.9.0[info]    using sbt.DefaultProject with sbt 0.7.7 and Scala 2.7.7> update[info] [info] == update ==[warn] No dependency configuration found, using defaults.[info] :: retrieving :: taobao#scala-object-using-sbt_2.9.0 [sync][info] confs: [default][info] 0 artifacts copied, 0 already retrieved (0kB/49ms)[info] == update ==[success] Successful.[info] [info] Total time: 1 s, completed Oct 11, 2011 10:31:15 PM> compile[info] [info] == compile ==[info]   Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.[info] Compiling main sources...[info] Compilation successful.[info]   Post-analysis: 18 classes.[info] == compile ==[success] Successful.[info] [info] Total time: 9 s, completed Oct 11, 2011 10:31:27 PM> run[info] [info] == copy-resources ==[info] == copy-resources ==[info] [info] == compile ==[info]   Source analysis: 0 new/modified, 0 indirectly invalidated, 0 removed.[info] Compiling main sources...[info] Nothing to compile.[info]   Post-analysis: 18 classes.[info] == compile ==[info] [info] == run ==[info] Running Pi AKKA_HOME is defined as [/home/shawny/software/akka-microkernel-1.1.3], loading config from [/home/shawny/software/akka-microkernel-1.1.3/config/akka.conf].Pi estimate: 3.1415926435897883Calculation time: 859 millis[info] == run ==[success] Successful.[info] [info] Total time: 2 s, completed Oct 11, 2011 10:31:32 PM

Ref: http://akka.io/docs/akka/1.1.1/intro/getting-started-first-scala.html
        https://github.com/jboner/akka
        http://akka.io/
原创粉丝点击