Akka 如何到达集群中的远程参与者

Akka how to reach remote actors in cluster

首先我想说我对 Akka 和 actors 很陌生:)

我想创建一个分布式应用程序。我会将应用程序拆分为 Web 部分 (REST API) 和用户管理部分。但是从应用程序的另一部分访问参与者的正确方法是什么?

我知道我可以通过提供其地址来访问演员选择 (https://doc.akka.io/docs/akka/2.5/remoting.html#looking-up-remote-actors),但是有没有一种方法可以让我不必使用地址?

我只想创建一个系统,无需使用他们的地址即可轻松联系到远程参与者。

也许你可以看看 Distributed Publish Subscribe in Cluster

但限制是:托管本地 actor 的本地 actorsystem 和托管远程 actor 的远程 actorsystem 应配置为 akka cluster

如果集群可以成为你的设计,那么你可以做如下:

远程部分:

class Subscriber extends Actor with ActorLogging {
  import DistributedPubSubMediator.{ Subscribe, SubscribeAck }
  val mediator = DistributedPubSub(context.system).mediator
  // subscribe to the topic named "content"
  mediator ! Subscribe("content", self)

  def receive = {
    case s: String ⇒
      log.info("Got {}", s)
    case SubscribeAck(Subscribe("content", None, `self`)) ⇒
      log.info("subscribing")
  }
}

本地部分:

class Publisher extends Actor {
  import DistributedPubSubMediator.Publish
  // activate the extension
  val mediator = DistributedPubSub(context.system).mediator

  def receive = {
    case in: String ⇒
      val out = in.toUpperCase
      mediator ! Publish("content", out)
  }
}

远程部分actor订阅content topic,如果本地部分想与远程对话,它可以发布消息到content topic

希望它能给你一些想法。

在 Cluster Sharding 中,actor 身份是 persistanceId 并且必须是您发送到整个集群的消息的一部分。这就是为什么你需要定义 extractEntityId.

在文档中阅读更多内容: https://doc.akka.io/docs/akka/2.5/cluster-sharding.html