Akka:如何启动一个简单的本地集群?

时间:2016-07-04 10:28:39

标签: scala akka akka-cluster

akka {
  actor {
    provider = "akka.cluster.ClusterActorRefProvider"
  }
  remote {
    enabled-transports = ["akka.remote.netty.tcp"]
    netty.tcp {
      hostname = "127.0.0.1"
      port = 0
    }
  }
}

akka.cluster {
  seed-nodes = [
    "akka.tcp://MyCluster@127.0.0.1:2551",
    "akka.tcp://MyCluster@127.0.0.1:2552"
  ]
}

object AndromedaApiClusterActivator extends App {
  val system = ActorSystem("MyCluster", ConfigFactory.load())
  val clusterController = system.actorOf(Props[MyCluster], name = "MyCluster")
}


class MyCluster extends Actor  {

  val log = Logging(context.system, this)
  val cluster = Cluster(context.system)

  override def preStart() {
    cluster.subscribe(self, classOf[MemberEvent], classOf[UnreachableMember])
  }

  override def postStop() {
    cluster.unsubscribe(self)
  }

  override def receive = {
    case x: MemberEvent => log.info("MemberEvent: {}", x)
    case x: UnreachableMember => log.info("UnreachableMember {}: ", x)
  }

}

当我跑步时,我得到:

Association with remote system [akka.tcp://MyCluster@127.0.0.1:2552] has failed, address is now gated for [5000] ms. Reason: [Association failed with [akka.tcp://MyCluster@127.0.0.1:2552]] Caused by: [Connection refused: /127.0.0.1:2552]
Association with remote system [akka.tcp://MyCluster@127.0.0.1:2551] has failed, address is now gated for [5000] ms. Reason: [Association failed with [akka.tcp://MyCluster@127.0.0.1:2551]] Caused by: [Connection refused: /127.0.0.1:2551]

我找不到解释。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

您应首先启动2个节点,然后连接到它们。为了说明这一点,我将在一个App内创建两个系统,但您可以运行App的2个实例,并在命令行中指定不同的配置/端口。

object Main extends App {
  val system1 = ActorSystem("MyCluster1", ConfigFactory.load("node1.conf"))
  val system2 = ActorSystem("MyCluster2", ConfigFactory.load("node2.conf"))
  val clusterController = system1.actorOf(Props[MyCluster], name = "MyCluster1")
}

application.conf

akka {
  actor {
    provider = "akka.cluster.ClusterActorRefProvider"
  }
  remote {
    enabled-transports = ["akka.remote.netty.tcp"]
    netty.tcp {
      hostname = "127.0.0.1"
      port = 2552
    }
  }
}

akka.cluster {
  seed-nodes = [
    "akka.tcp://MyCluster1@127.0.0.1:2552",
    "akka.tcp://MyCluster2@127.0.0.1:2553"
  ]
}

要启动其他节点,我建议使用node1.conf指定不同的配置:

include "application"

akka.remote.netty.tcp.port = 2552

node2.conf

include "application"

akka.remote.netty.tcp.port = 2553