Akka学习笔记(1)-HelloWorld

Akka入门示例-HelloWorld

参考自:edwardsbean
- 创建Model

//case model
object Greeter{
  case object Greet
  case object Done
}
  • 创建执行任务的子Actor
class Greeter extends Actor {
   //处理接收到的消息
   def receive = {
     case Greeter.Greet => {
        println("Hello World")
        sender ! Greeter.Done
     }
   }
   //终止Actor的hook方法
   override def postStop = {
       println("greeter stoped")
   }
}
  • 创建根级Actor
class HelloWorld extends Actor{

    //启动Actor时的hook方法
    override def preStart(): Unit = {
       //创建并启动一个子Actor, 向其发送消息
       val greeter = context.actorOf(Props[Greeter], name = "greeter")
       greeter ! Greeter.Greet
    }
    //终止Actor时的hook方法
    override def postStop = {
       println("hello world post stop")
    }

    def receive = {
        //任务完成,终止Actor
        case Greeter.Done => context.stop(self)
    }
}
  • 执行该Akka Actor
object Main extends App {
     //akka.Main.main(Array(classOf[HelloWorld].getName))
     val system = ActorSystem("HelloWorld")
     system.actorOf(Props[HelloWorld], name = "helloworld")
}

执行结果如下:

[DEBUG] [02/15/2016 11:31:40.644] [main] [EventStream(akka://HelloWorld)] logger log1-Logging$DefaultLogger started
[DEBUG] [02/15/2016 11:31:40.645] [main] [EventStream(akka://HelloWorld)] Default Loggers started
[INFO] [02/15/2016 11:31:40.754] [main] [Remoting] Starting remoting
[INFO] [02/15/2016 11:31:41.105] [main] [Remoting] Remoting started; listening on addresses :[akka.tcp://[email protected]:5515]
[INFO] [02/15/2016 11:31:41.108] [main] [Remoting] Remoting now listens on addresses: [akka.tcp://[email protected]:5515]
Hello World
greeter stoped
hello world post stop


如何发布和使用Akka程序


Akka的使用方式一般有两种:

  • 一种是作为普通jar包使用
  • 一种是作为服务使用

第一种使用方式比较好理解,第二种使用方式就是将依赖包与自定义actor一起打包,然后启动自定义actor,下面是一个示例:

package zender.akka.test.one
import akka.actor.{Actor, ActorSystem, Props}
import akka.kernel.Bootable
case object Start

class HelloActor extends Actor {
   //创建一个子actor, worldActor
   val worldActor = context.actorOf(Props[WorldActor], name = "worldActor")

   def receive = {
     case Start => { worldActor ! "hello"}
     case message: String => {
         //打印子Actor返回的数据
         println("Receive 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("HelloWorldSystem")

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

你可能感兴趣的:(akka)