前提
拥有scala+akka的环境
使用sbt搭建akka的可以看我上篇文章
使用actor最好有一定的scala基础,比如模式匹配,“!” 感叹号是向 Actor 发送消息,其实 “!” 就是一个方法名,当参数只有一个数,可省略点号与圆括号。标准的写法是
helloActor.!("hey")
直接上代码
先从最简单的例子开始:
package priv.xxx
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
class MyActor extends Actor {
def receive = {
case "hey" => println("hey yourself")
case _ => println("nothing")
}
}
object Test_Actor1 {
def main(args: Array[String]): Unit = {
val system = ActorSystem("MySystem")
val myActor = system.actorOf(Props[MyActor], name = "MyActor")
myActor ! "hey"
// 相当于 myActor.!("hey")
myActor ! "hello"
// 终止ActorSystem
system.terminate()
}
}
输出结果:
hey yourself
nothing
进程已结束,退出代码为 0
然后我自己扩展了一下,写了两个对象(man和woman)对话的场景:
package priv.xxx
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
case class Message(receive: ActorRef,send: ActorRef, msg:String)
class Man extends Actor{
def receive = {
case x:Message => {
val woman_msg = x.msg
println(x.msg)
val woman = x.send
val man = x.receive
if (woman_msg.equals("hello man")){
woman ! Message(woman,man,"hello girl")
}else if(woman_msg.equals("今天天气真不戳")) {
woman ! Message(woman,man,"是啊")
} else if(woman_msg.equals("下次见")){
woman ! Message(woman,man,"88")
}else{
println("鬼!")
}
}
}
}
class Woman extends Actor{
def receive = {
case x:Message => {
val man_msg = x.msg
println(x.msg)
val man = x.send
val woman = x.receive
if (man_msg.equals("hello girl")){
man ! Message(man,woman,"今天天气真不戳")
}else if(man_msg.equals("是啊")) {
man ! Message(man,woman,"下次见")
} else if(man_msg.equals("88")){
man ! Message(man,woman,"88")
}else{
println("鬼!")
}
}
}
}
object Test_Actor2 {
def main(args: Array[String]): Unit = {
val system = ActorSystem("MySystem")
val man = system.actorOf(Props[Man], name = "Man")
val woman = system.actorOf(Props[Woman], name = "Woman")
man ! Message(man,woman,"hello man")
system.terminate()
}
}
输出结果:
hello man
hello girl
今天天气真不戳
是啊
下次见
88
88
鬼!
进程已结束,退出代码为 0
参考:1、Akka Actor从最简单的例子开始:https://yanbin.blog/akka-actor-start-with-easy-example
2、Akka终止Actor用法示例详解:http://www.srcmini.com/34648.html
简单的例子灵感来源:https://alvinalexander.com/scala/simple-scala-akka-actor-examples-hello-world-actors/