Akka学习笔记(一):创建Hello World工程


Akka学习笔记(一):创建Hello World工程

创建工程

使用IDEA,创建SBT工程,在build.sbt中添加akka依赖:

name := "My Project"

version := "1.0"

scalaVersion := "2.10.4"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies +=
  "com.typesafe.akka" %% "akka-actor" % "2.3.4"

如果SBT版本低于0.12,需要更改依赖为:

libraryDependencies +=
  "com.typesafe.akka" % "akka-actor_2.10" % "2.3.4"

其他IDE,构建方式,请看here

Hello World

完整代码可以在这里下载

HelloWorld.scala

我们创建HelloWorld.scala,代码如下:

class HelloWorld extends Actor {

  override def preStart(): Unit = {
    // create the greeter actor
    val greeter = context.actorOf(Props[Greeter], "greeter")
    // tell it to perform the greeting
    greeter ! Greeter.Greet
  }

  def receive = {
    // when the greeter is done, stop this actor and with it the application
    case Greeter.Done => context.stop(self)
  }
}

HelloWorld是我们这个应用的中心(main),它会启动和关闭所有actor(Greeter)

Greeter.scala
object Greeter {
  case object Greet
  case object Done
}

class Greeter extends Actor {
  def receive = {
    case Greeter.Greet =>
      println("Hello World!")
      sender() ! Greeter.Done
  }
}

Greeter的内容很简单,一旦它被创建,等待接受消息,打印Hello World!,并告诉调用者Greeter.Done

Main.scala

让我们运行这个程序吧,很简单,指定负责调度的Actor:HelloWorld就可以了:

object Main {

  def main(args: Array[String]): Unit = {
    akka.Main.main(Array(classOf[HelloWorld].getName))
  }
}

运行:

Hello World!
[INFO] [07/25/2014 15:11:43.147] [Main-akka.actor.default-dispatcher-4] [akka://Main/user/app-terminator] application supervisor has terminated, shutting down

如何发布和使用Akka程序

有两种方式:

  • 当做jar包使用
  • 作为单独的服务,使用Akka Microkernel,详见here
Akka Microkernel

大致就是,把依赖包放到lib/*,通过启动类如(HelloKernel)启动:

bin/akka sample.kernel.hello.HelloKernel

helloKernel代码如下:

package sample.kernel.hello

import akka.actor.{ Actor, ActorSystem, Props }
import akka.kernel.Bootable

case object Start

class HelloActor extends Actor {
  val worldActor = context.actorOf(Props[WorldActor])

  def receive = {
    case Start => worldActor ! "Hello"
    case message: String =>
      println("Received message '%s'" format message)
  }
}

class WorldActor extends Actor {
  def receive = {
    case message: String => sender() ! (message.toUpperCase + " world!")
  }
}
 //启动类,需要继承Bootable
class HelloKernel extends Bootable {
  val system = ActorSystem("hellokernel")

  def startup = {
    system.actorOf(Props[HelloActor]) ! Start
  }

  def shutdown = {
    system.shutdown()
  }
}

   
   
   
   

你可能感兴趣的:(scala,akka)