Pergunta

I am using akka with play. And I want something to be done only once when a new leader is up

I am going to find something like , in other words, I am looking for something like this.

class LeaderUpHook {   
    def onLeaderUp {
        log.log("a new leader is up")   
   } 
}

I search the clustering doc , but still don't how to do

Foi útil?

Solução

You should be able to use the cluster events to figure this out. I'm basing my code example off of the documentation under the Subscribe to Cluster Events section of the docs here. So in short, you basically create an actor that subscribes into relevant cluster events in order to determine who the leader is and when that leader is up. That actor could look like this:

import akka.actor._
import akka.cluster._

class LeaderUpHandler extends Actor{
  import ClusterEvent._

  val cluster = Cluster(context.system)
  cluster.subscribe(self, classOf[MemberUp])
  cluster.subscribe(self, classOf[LeaderChanged])
  var leader:Option[Address] = None

  def receive = {
    case  state:CurrentClusterState => 
      println(s"Got current state: $state")

    case MemberUp(member) =>
      println(s"member up: $member")
      leader.filter(_ == member.address) foreach{ address => 
        println("leader is now up...")
      }

    case LeaderChanged(address) => 
      println(s"leader changed: $address")
      leader = address
  }
}

Then to test this code, you could do the following:

val cfg = """
  akka {
      actor {
        provider = "akka.cluster.ClusterActorRefProvider"               
      }
      remote {
        netty.tcp {
            hostname = "127.0.0.1"
            port = 2552 
        }    
      }
      cluster {
        seed-nodes = [
            "akka.tcp://clustertest@127.0.0.1:2552"
          ]
        auto-down = on
      }     
  }    

"""
val config = ConfigFactory.parseString(cfg).withFallback(ConfigFactory.load)
val system = ActorSystem("clustertest", config)
system.actorOf(Props[LeaderUpHandler])  

When you run the above code, you should see the leader get determined to be up. This is an oversimplified example; I'm just trying to show that you can use the cluster events to find what you are looking for.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top