scala_akka_Actor的简单例子

前提

拥有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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值