【问题标题】:How to implement parent-children model with Akka in Scala?如何在 Scala 中使用 Akka 实现父子模型?
【发布时间】:2017-03-21 14:22:58
【问题描述】:

我想用 Scala 和 Akka 实现一个小的 HTTP 服务器。具体来说,我想要两种演员:EmployeeRouterActor 和 EmployeeEchoActor。

第一个,我想像路由器一样使用它,我的意思是,那个actor接收所有消息,它必须为每条消息创建一个孩子(在本例中为EmployeeEchoActor)。

每个孩子都会收到一条员工消息,它必须返回一个包含员工信息的字符串。

而且,在孩子完成它的过程之后,孩子必须死。我认为父母必须控制孩子的生命周期。

在 Akka 文档中,我只看到使用单个子级,例如 this

我该怎么做? Akka 网站是否有任何示例或任何其他文档?

【问题讨论】:

    标签: scala akka actor


    【解决方案1】:

    类似这样的:

    object EmployeeRouterActor {
      final case class Employee(id: String, name: String)
      final case object StopChild
      final case class ChildResponse(id: String, data: String)
    }
    
    final class EmployeeRouterActor extends Actor {
      import EmployeeRouterActor._
    
      // Make a map which will store child actors
      private var children = Map.empty[String, ActorRef]
    
      override def receive: Receive = {
        case e @ Employee(id, _)  => getChild(id) ! e
        case ChildResponse(id, _) => stopChild(id)
      }
    
      // Check whether child exists in context of this actor.
      // If it doesn't, create new one.
      private def getChild(id: String): ActorRef =
        context.child(id).getOrElse {
          val child = context.actorOf(EmployeeEchoActor.apply(), id)
          children += (id -> child)
          child
        }
    
      private def stopChild(id: String) = {
        children(id) ! StopChild
        children -= id
      }
    }
    
    object EmployeeEchoActor {
      def apply(): Props = Props(new EmployeeEchoActor)
    }
    
    final class EmployeeEchoActor extends Actor {
      // self.path.name to access its id
      override def receive: Receive = {
        case EmployeeRouterActor.Employee =>
          // do stuff with Employee message...
          context.parent ! EmployeeRouterActor.ChildResponse(self.path.name, "Done!") // Or pipeTo(context.parent)
        case EmployeeRouterActor.StopChild => context.stop(self)
      }
    }
    

    基本上,子actors被创建并存储在Map中。当他们完成任务时,他们会向他们的父母回复回复消息,然后他们会阻止他们。

    【讨论】:

    • 哇,感谢您的回复。我将在我的项目中检查您的解决方案。
    • 我实现了这个解决方案,它工作正常,但当 EmployeeRouterActor 在收到 ChildResponse 后发回响应时,我总是收到死信。我正在做。非常感谢您的帮助。
    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2011-04-28
    • 2016-02-28
    • 2012-04-22
    • 2020-05-01
    • 1970-01-01
    相关资源
    最近更新 更多