Saturday, November 10, 2012

Minimal Akka Hello World with SBT

  1. Create a directory for our project files.
  2. Create helloworld.scala in the project directory.
    import akka.actor._
    import akka.pattern.ask
    import akka.util.duration._
    import akka.util.Timeout
    
    case class Print(s: String)
    case object PrintAck
    
    class Printer extends Actor {
      def receive = {
        case Print(s) => {
          println(s)
          sender ! PrintAck
        }
      }
    }
    
    object HelloWorld {
      def main(args: Array[String]) {
        val system = ActorSystem("HelloWorld")
        val printer = system.actorOf(Props[Printer])
        implicit val timeout = Timeout(5 seconds)
        (printer ? Print("Hello world")) onComplete {
          _ => system.shutdown()
        }
      }
    }
    
  3. Create build.sbt in the project directory.
    name := "Akka Hello World"
     
    version := "1.0"
     
    scalaVersion := "2.9.2"
     
    resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
     
    libraryDependencies += "com.typesafe.akka" % "akka-actor" % "2.0.3"
    
  4. Download the latest SBT launch JAR and install it somewhere. This JAR bootstraps SBT and builds the project. I downloaded the 0.12.1 version. You can get the location of the latest version from the SBT Manual Installation instructions on the SBT website.
  5. Go to your project directory and run SBT. The following has the recommended VM options for running on Windows. Replace XXX with your SBT installation location.
    $ java -Xmx512M -jar XXX/sbt-launch-0.12.1.jar
    [info] Set current project to Akka Hello World (...)
    
  6. Run the program!
    > run
    [info] Running HelloWorld
    Hello world
    [success] Total time: 6 s, completed 11/11/2012 11:02:21 AM
    

See also:

No comments:

Post a Comment