如何通过动物园管理员策展人失去领导力时观看沉默?

时间:2016-09-09 08:10:10

标签: apache-zookeeper apache-curator

正如我们所知,当客户获得领导时,会占用领导者,但文件并没有告诉我客户何时失去了领导权!!!所以,如何在失去领导权时观看沉默zookeeper策展人?

问题二:为什么我的客户输了,我无法调试stateChanged(...)的想法?

这里是我的代码,期待你的答案很好,thx

公共类ExampleClient extends LeaderSelectorListenerAdapter实现了Closeable {

private final String name;
private final LeaderSelector  leaderSelector;
private final AtomicInteger leaderCount = new AtomicInteger();//用于记录领导次数

public ExampleClient(CuratorFramework client,String path,String name) {
    this.name = name;
    leaderSelector = new LeaderSelector(client, path, this);
    leaderSelector.autoRequeue();//保留重新获取领导权资格
}

public void start() throws IOException {
    leaderSelector.start();
}


@Override
public void close() throws IOException {
    leaderSelector.close();
}


@Override
public void stateChanged(CuratorFramework client, ConnectionState newState)
{
    if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST) ) {

        log.info("stateChanged !!!");

        throw new CancelLeadershipException();
    }
}

/**
 * will be invoded when get leadeship
 * @param client
 * @throws Exception
 */
@Override
public void takeLeadership(CuratorFramework client) throws Exception {
    final int waitSeconds =(int)(Math.random()*5)+1;
    log.info(name + " is  the leader now,wait " + waitSeconds + " seconds!");
    log.info(name + " had been leader for " + leaderCount.getAndIncrement() + " time(s) before");
    try {
      /**/
        Thread.sleep(TimeUnit.SECONDS.toMillis(waitSeconds));

        //do something!!!

        /*while(true){
            //guarantee this client be the leader all the time!
        }*/
    }catch (InterruptedException e){
        log.info(name+" was interrupted!");
        Thread.currentThread().interrupt();
    }finally{
        log.info(name+" relinquishing leadership.\n");
    }
}

}

1 个答案:

答案 0 :(得分:0)

LeaderLatchListener有两个关于isLeader和notLeader的回调。一些例子, http://www.programcreek.com/java-api-examples/index.php?api=org.apache.curator.framework.recipes.leader.LeaderLatchListener