按ID获取或创建子actor

Ser*_*iGP 2 scala akka

我的系统中有两个演员.说话者和谈话.对话包括两个谈话者(现在).当发话方要加入对话,我应该检查是否存在会话(另一健谈创造了它),如果没有,创建它.我在我的Talker演员的方法中有这个代码:

  def getOrCreateConversation(conversationId: UUID): ActorRef = {

    // @TODO try to get conversation actor by conversationId
    context.actorSelection("user/conversation/" + conversationId.toString)

    // @TODO if it not exists... create it
    context.actorOf(Conversation.props(conversationId), conversationId.toString)
  }
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,当我用actorOf创建我的对话演员时,我作为第二个参数传递了conversationId.我这样做是为了方便搜索这个演员...这是正确的方法吗?

谢谢

编辑

感谢@Arne我终于做到了:

class ConversationRouter extends Actor with ActorLogging {
  def receive = {
    case ConversationEnv(conversationId, msg) =>
      val conversation = findConversation(conversationId) match {
        case None    => createNewConversation(conversationId)
        case Some(x) => x
      }
      conversation forward msg
  }

  def findConversation(conversationId: UUID): Option[ActorRef] = context.child(conversationId.toString)

  def createNewConversation(conversationId: UUID): ActorRef = {
    context.actorOf(Conversation.props(conversationId), conversationId.toString)
  }
}
Run Code Online (Sandbox Code Playgroud)

而且测试:

class ConversationRouterSpec extends ChatUnitTestCase("ConversationRouterSpec") {

  trait ConversationRouterSpecHelper {
    val conversationId = UUID.randomUUID()

    var newConversationCreated = false

    def conversationRouterWithConversation(existingConversation: Option[ActorRef]) = {
      val conversationRouterRef = TestActorRef(new ConversationRouter {
        override def findConversation(conversationId: UUID) = existingConversation

        override def createNewConversation(conversationId: UUID) = {
          newConversationCreated = true
          TestProbe().ref
        }
      })
      conversationRouterRef
    }
  }

  "ConversationRouter" should {
    "create a new conversation when a talker join it" in new ConversationRouterSpecHelper {
      val nonExistingConversationOption = None
      val conversationRouterRef = conversationRouterWithConversation(nonExistingConversationOption)

      conversationRouterRef ! ConversationEnv(conversationId, Join(conversationId))

      newConversationCreated should be(right = true)
    }

    "not create a new conversation if it already exists" in new ConversationRouterSpecHelper {
      val existingConversation = Option(TestProbe().ref)
      val conversationRouterRef = conversationRouterWithConversation(existingConversation)

      conversationRouterRef ! ConversationEnv(conversationId, Join(conversationId))

      newConversationCreated should be(right = false)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Arn*_*sen 8

确定演员的存在不能同步完成.所以你有几个选择.前两个在本质上更具概念性,用于说明进行异步查找,但我提供了更多关于actor的异步性质的参考.第三种可能是正确的做事方式:

1.使函数返回a Future[ActorRef]

def getOrCreateConversation(conversationId: UUID): Unit {
   context.actorSelection(s"user/conversation/$conversationId")
     .resolveOne()
     .recover { case _:Exception =>
        context.actorOf(Conversation.props(conversationId),conversationId.toString)
      }
}
Run Code Online (Sandbox Code Playgroud)

2.制作它Unit并让它发ActorRef回给你当前的演员

与上面几乎相同,但是现在我们将未来传递回当前的actor,以便可以在调用actor的receive循环的上下文中处理已解析的actor :

def getOrCreateConversation(conversationId: UUID): Unit {
   context.actorSelection(s"user/conversation/$conversationId")
     .resolveOne()
     .recover { case _:Exception =>
        context.actorOf(Conversation.props(conversationId),conversationId.toString)
      }.pipeTo(self)
}
Run Code Online (Sandbox Code Playgroud)

3.创建一个路由器actor,您将Id"ed"消息发送给它,然后创建/解析该子节点并转发该消息

我说这可能是正确的方法,因为你的目标似乎是在特定的命名路径上进行廉价查找.您给出的示例假设函数始终在路径中的actor内调用,/user/conversation否则context.actorOf将不会创建子项/user/conversation/{id}/.

也就是说,你手上有一个路由器模式,你创建的子节点已经被子集合中的路由器所知.此模式假设您在任何会话消息周围都有一个信封,如下所示:

case class ConversationEnv(id: UUID, msg: Any)
Run Code Online (Sandbox Code Playgroud)

现在,所有会话消息都被发送到路由器而不是直接发送给会话子.路由器现在可以在其子集合中查找子节点:

def receive = {
  case ConversationEnv(id,msg) =>
    val conversation = context.child(id.toString) match {
      case None => context.actorOf(Conversation.props(id),id.toString)
      case Some(x) => x
    }
    conversation forward msg
}
Run Code Online (Sandbox Code Playgroud)

额外的好处是你的路由器也是会话主管,所以如果会话孩子死了,它可以处理它.不让孩子暴ActorRef露在外面也有一个好处,就是你可以让它在闲置时死去,并在下一个消息收据上重新创建,等等.