Actor - Creating Actors

创建Actor - 最佳实践

import akka.actor.ActorSystem

object AkkaActor extends App {

import DemoActor._

println("Hello, world!")
val system = ActorSystem("mySystem")
val demoActor = system.actorOf(props(42), "demoActor")
println(s"demoActor created !")
demoActor ! 88
}

import akka.actor.{Actor, ActorLogging, Props}


object DemoActor {
/**
* Create Props for an actor of this type.
*
* @param magicNumber The magic number to be passed to this actor’s constructor.
* @return a Props for creating this actor, which can then be further configured
* (e.g. calling `.withDispatcher()` on it)
*/
def props(magicNumber: Int): Props = Props(new DemoActor(magicNumber))
}

class DemoActor(magicNumber: Int) extends Actor with ActorLogging{

import MyActor._

def receive = {
case x: Int =>
println(s"magicNumber: $magicNumber - params: $x")
val myActor = context.actorOf(MyActor.props, "myActor")
println(s"create myActor: ${myActor.path}")
myActor ! Greeting("Vincent Guo")
}
}
import akka.actor.{Actor, Props}
import akka.event.Logging

object MyActor {

case class Greeting(from: String)

case object Goodbye

def props: Props = Props(new MyActor())
}

class MyActor extends Actor {
val log = Logging(context.system, this)

import MyActor._

def receive = {
case Greeting(greeter) => log.info(s"I was greeted by $greeter.")
case Goodbye => log.info("Someone said goodbye to me.")
}
}

创建顶级Actor val system = ActorSystem("mySystem")

  • 推荐是半生对象里创建Actor(可接受参数)
  • 里面还可以定义接受的事件

Output

Hello, world!
demoActor created !
magicNumber: 42 - params: 88
create myActor: akka://mySystem/user/demoActor/myActor
[INFO] [04/27/2017 18:24:20.257] [mySystem-akka.actor.default-dispatcher-2] [akka://mySystem/user/demoActor/myActor] I was greeted by Vincent Guo.