Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka: How to find the current nodes in a cluster?

From within an Akka actor, how can you find out the nodes of the cluster? That is, the nodes which the local node considers to be currently accessible.

Thanks, - Daniel

like image 452
Daniel Winterstein Avatar asked Jul 28 '13 19:07

Daniel Winterstein


2 Answers

You actually do not need to subscribe to ClusterDomainEvent or MemberEvent. You can just access the state member of the Cluster extension, e.g.,

val cluster = akka.cluster.Cluster(context.system)

val members = cluster.state.members.filter(_.status == MemberStatus.Up)
like image 94
Jeffrey Aguilera Avatar answered Oct 16 '22 17:10

Jeffrey Aguilera


Tweaked sample from Typesafe Activator tutorial:

case object GetNodes

class MemberListener extends Actor {

  val cluster = Cluster(context.system)

  override def preStart(): Unit =
    cluster.subscribe(self, classOf[MemberEvent])

  override def postStop(): Unit =
    cluster unsubscribe self

  var nodes = Set.empty[Address]

  def receive = {
    case state: CurrentClusterState =>
      nodes = state.members.collect {
        case m if m.status == MemberStatus.Up => m.address
      }
    case MemberUp(member) =>
      nodes += member.address
    case MemberRemoved(member, _) =>
      nodes -= member.address
    case _: MemberEvent ⇒ // ignore
    case GetNodes =>
      sender ! nodes
  }
}
like image 36
Patrik Nordwall Avatar answered Oct 16 '22 17:10

Patrik Nordwall