classHelloextendsActor{ defreceive= { case msg: String => println("hello " + msg) case _ => println("unexpected message.") } }
启动
创建Actor实例需要通过 ActorSystem 。
val system = ActorSystem("HelloSystem") val hello = system.actorOf(Props[Hello], name = "hello") val hello1 = system.actorOf(Props[Hello]) val hello2 = system.actorOf(Props(newHello()))
如果要在 Actor 中继续创建子 Actor,需要使用内置的 ActorContext 对象。
context.actorOf(Props[children], name = "children")
objectHengHaextendsApp{ val system = ActorSystem("HengHaSystem") val ha = system.actorOf(Props[Ha], name = "ha") val heng = system.actorOf(Props(newHeng(ha)), name = "heng")
heng ! "start" }
classHeng(ha: ActorRef) extendsActor{ defreceive= { case"start" => ha ! "heng" case"ha" => println("哈") ha ! "heng" case _ => println("heng what?") } }
object Local extends App { val system = ActorSystem("LocalSystem") val localActor = system.actorOf(Props[LocalActor], name = "LocalActor") // the local actor localActor ! "START" // start the action }
classLocalActorextendsActor{ // create the remote actor val remote = context.actorSelection("akka.tcp://HelloRemoteSystem@127.0.0.1:5150/user/RemoteActor") var counter = 0
defreceive= { case"START" => remote ! "Hello from the LocalActor" case msg: String => println(s"LocalActor received message: '$msg'")
if (counter < 5) { sender ! "Hello back to you" counter += 1 } } }
objectHelloRemoteextendsApp{ val system = ActorSystem("HelloRemoteSystem") val remoteActor = system.actorOf(Props[RemoteActor], name = "RemoteActor")
remoteActor ! "The RemoteActor is alive" }
classRemoteActorextendsActor{ defreceive= { case msg: String => println(s"RemoteActor received message '$msg'") sender ! "Hello from the RemoteActor" } }