简介: 本将主要内容:
1. !消息发送,Fire-and-Forget消息模型
2. ?消息发送,Send-And-Receive-Future消息模型 Akka提供了两种消息模型:fire-and-forget和Send-And-Receive-Future。
fire-and-forget是一种单向消息发送模型,指的是异步发送消息,通过异步发送消息且消息发送后可以立即返回,

本将主要内容:
1. !消息发送,Fire-and-Forget消息模型
2. ?消息发送,Send-And-Receive-Future消息模型
Akka提供了两种消息模型:fire-and-forget和Send-And-Receive-Future。fire-and-forget是一种单向消息发送模型,指的是异步发送消息,通过异步发送消息且消息发送后可以立即返回,Akka中使用?方法进行fire-and-forget消息发送,如stringActor!”Creating Actors with implicit val context”,它的意思是当前发送方Aactor向stringActor发送字符串消息”Creating Actors with implicit val context”,发送完该消息后立即返回,而无需等待stringActor的返回,!还有个重载的方法tell;Send-And-Receive-Future指的是异步发送消息则是一种双向消息发送模型,向目标Actor发送完消息后,然后返回一个Future作为后期可能的返回,当前发送方Actor将等待目标Actor的返回,Akka中使用?方法进行Send-And-Receive-Future消息的发送,它也同样有一个重载的方法ask

1. !消息发送,Fire-and-Forget消息模型

  1. /**
  2. * 消息处理:!(Fire-Forget)
  3. */
  4. object Example12 extends App{
  5. import akka.actor.Actor
  6. import akka.actor.Props
  7. import akka.event.Logging
  8. import akka.actor.ActorSystem
  9. //定义几种不同的消息
  10. case class Start(var msg:String)
  11. case class Run(var msg:String)
  12. case class Stop(var msg:String)
  13. class ExampleActor extends Actor {
  14. val other = context.actorOf(Props[OtherActor], "OtherActor")
  15. val log = Logging(context.system, this)
  16. def receive={
  17. //使用fire-and-forget消息模型向OtherActor发送消息,隐式地传递sender
  18. case Start(msg) => other ! msg
  19. //使用fire-and-forget消息模型向OtherActor发送消息,直接调用tell方法,显式指定sender
  20. case Run(msg) => other.tell(msg, sender)
  21. }
  22. }
  23. class OtherActor extends Actor{
  24. val log = Logging(context.system, this)
  25. def receive ={
  26. case s:String=>log.info("received message:\n"+s)
  27. case _ log.info("received unknown message")
  28. }
  29. }
  30. //创建ActorSystem,ActorSystem为创建和查找Actor的入口
  31. //ActorSystem管理的Actor共享配置信息如分发器(dispatchers)、部署(deployments)等
  32. val system = ActorSystem("MessageProcessingSystem")
  33. //创建ContextActor
  34. val exampleActor = system.actorOf(Props[ExampleActor],name="ExampleActor")
  35. //使用fire-and-forget消息模型向exampleActor发送消息
  36. exampleActor!Run("Running")
  37. exampleActor!Start("Starting")
  38. //关闭ActorSystem
  39. system.shutdown()
  40. }

代码运行结果如下:

  1. [INFO] [03/20/2016 20:57:43.665] [MessageProcessingSystem-akka.actor.default-dispatcher-5] [akka://MessageProcessingSystem/user/ExampleActor/OtherActor] received message:
  2. Running
  3. [INFO] [03/20/2016 20:57:43.672] [MessageProcessingSystem-akka.actor.default-dispatcher-5] [akka://MessageProcessingSystem/user/ExampleActor/OtherActor] received message:
  4. Starting

在ExampleActor中,通过隐式变量context创建了OtherActor实例:val other = context.actorOf(Props[OtherActor], “OtherActor”),在ExampleActor的receive方法中,处理两种不同类型的消息例如:

  1. //使用fire-and-forget消息模型向OtherActor发送消息,隐式地传递sender
  2. case Start(msg) => other ! msg
  3. //使用fire-and-forget消息模型向OtherActor发送消息,直接调用tell方法,显式指定sender
  4. case Run(msg) => other.tell(msg, sender)

处理Start类型的消息时,直接使用!进行消息发送,而处理Run类型的消息时,使用的是tell方法,可以看到使用tell方法需要显式地指定其sender,而使用!进行消息发送则不需要,事实上!方法通过隐式值传入需要的Sender,对比!与tell方法的定义便很容易理解

  1. //!方法的定义
  2. def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit
  3. //tell方法的定义
  4. final def tell(msg: Any, sender: ActorRef): Unit = this.!(msg)(sender)

可以看到,tell方法的实现依赖于!方法。如果在一个Actor当中使用!方法时,例如ExampleActor中使用的other ! msg向OtherActor发送消息,则sender隐式为ExampleActor,如果不是在Actor中使用则默认为Actor.noSender,即sender为null。

2. ?消息发送,Send-And-Receive-Future消息模型

理解了Fire-And-Forget消息模型后,接着对Send-And-Receive-Future消息模型进行介绍,下面的代码给出了其使用示例。

  1. /**
  2. * 消息处理:?(Send-And-Receive-Future)
  3. */
  4. object Example13 extends App{
  5. import akka.actor.Actor
  6. import akka.actor.Props
  7. import akka.event.Logging
  8. import akka.actor.ActorSystem
  9. import scala.concurrent.Future
  10. import akka.pattern.ask
  11. import akka.util.Timeout
  12. import scala.concurrent.duration._
  13. import akka.pattern.pipe
  14. import scala.concurrent.ExecutionContext.Implicits.global
  15. //消息:个人基础信息
  16. case class BasicInfo(id:Int,val name:String, age:Int)
  17. //消息:个人兴趣信息
  18. case class InterestInfo(id:Int,val interest:String)
  19. //消息: 完整个人信息
  20. case class Person(basicInfo: BasicInfo,interestInfo: InterestInfo)
  21. //基础信息对应Actor
  22. class BasicInfoActor extends Actor{
  23. val log = Logging(context.system, this)
  24. def receive = {
  25. //处理送而来的用户ID,然后将结果发送给sender(本例中对应CombineActor)
  26. case id:Int log.info("id="+id);sender!new BasicInfo(id,"John",19)
  27. case _ log.info("received unknown message")
  28. }
  29. }
  30. //兴趣爱好对应Actor
  31. class InterestInfoActor extends Actor{
  32. val log = Logging(context.system, this)
  33. def receive = {
  34. //处理发送而来的用户ID,然后将结果发送给sender(本例中对应CombineActor)
  35. case id:Int log.info("id="+id);sender!new InterestInfo(id,"足球")
  36. case _ log.info("received unknown message")
  37. }
  38. }
  39. //Person完整信息对应Actor
  40. class PersonActor extends Actor{
  41. val log = Logging(context.system, this)
  42. def receive = {
  43. case person: Person =>log.info("Person="+person)
  44. case _ log.info("received unknown message")
  45. }
  46. }
  47. class CombineActor extends Actor{
  48. implicit val timeout = Timeout(5 seconds)
  49. val basicInfoActor = context.actorOf(Props[BasicInfoActor],name="BasicInfoActor")
  50. val interestInfoActor = context.actorOf(Props[InterestInfoActor],name="InterestInfoActor")
  51. val personActor = context.actorOf(Props[PersonActor],name="PersonActor")
  52. def receive = {
  53. case id: Int =>
  54. val combineResult: Future[Person] =
  55. for {
  56. //向basicInfoActor发送Send-And-Receive-Future消息,mapTo方法将返回结果映射为BasicInfo类型
  57. basicInfo <- ask(basicInfoActor, id).mapTo[BasicInfo]
  58. //向interestInfoActor发送Send-And-Receive-Future消息,mapTo方法将返回结果映射为InterestInfo类型
  59. interestInfo <- ask(interestInfoActor, id).mapTo[InterestInfo]
  60. } yield Person(basicInfo, interestInfo)
  61. //将Future结果发送给PersonActor
  62. pipe(combineResult).to(personActor)
  63. }
  64. }
  65. val _system = ActorSystem("Send-And-Receive-Future")
  66. val combineActor = _system.actorOf(Props[CombineActor],name="CombineActor")
  67. combineActor ! 12345
  68. Thread.sleep(5000)
  69. _system.shutdown
  70. }

代码运行结果如下:

  1. [INFO] [03/20/2016 22:55:11.208] [Send-And-Receive-Future-akka.actor.default-dispatcher-3] [akka://Send-And-Receive-Future/user/CombineActor/BasicInfoActor] id=12345
  2. [INFO] [03/20/2016 22:55:11.220] [Send-And-Receive-Future-akka.actor.default-dispatcher-2] [akka://Send-And-Receive-Future/user/CombineActor/InterestInfoActor] id=12345
  3. [INFO] [03/20/2016 22:55:11.223] [Send-And-Receive-Future-akka.actor.default-dispatcher-4] [akka://Send-And-Receive-Future/user/CombineActor/PersonActor] Person=Person(BasicInfo(12345,John,19),InterestInfo(12345,足球))

代码中定义了3种类型的消息,分别是个人基础信息case class BasicInfo(id:Int,val name:String, age:Int)、个人兴趣信息case class InterestInfo(id:Int,val interest:String)以及完整个人信息case class Person(basicInfo: BasicInfo,interestInfo: InterestInfo),然后为这3种类型的消息定义了相应的Actor即BasicInfoActor、InterestInfoActor和PersonActor,在CombineActor分别创建相应Actor的实例,receive方法中使用ask向BasicInfoActor、InterestInfoActor发送Send-And-Receive-Future模型消息,BasicInfoActor、InterestInfoActor中的receive方法接收到发送来的Int类型消息并分别使用!向CombineActor发送BasicInfo、InterestInfo消息,将结果保存在Future[Person]中,然后通过代码pipe(combineResult).to(personActor)将结果发送给PersonActor。