Created
February 19, 2013 10:33
-
-
Save definitelyMVP/4984723 to your computer and use it in GitHub Desktop.
a curator LeaderLatch example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.netflix.curator.framework.CuratorFramework; | |
import com.netflix.curator.framework.CuratorFrameworkFactory; | |
import com.netflix.curator.framework.recipes.leader.LeaderLatch; | |
import com.netflix.curator.framework.recipes.leader.Participant; | |
import com.netflix.curator.retry.ExponentialBackoffRetry; | |
import java.io.IOException; | |
/** | |
* @author yl | |
* @date 2013-02-19 | |
*/ | |
public class LeaderLatchExample { | |
private CuratorFramework client; | |
private String latchPath; | |
private String id; | |
private LeaderLatch leaderLatch; | |
public LeaderLatchExample(String connString, String latchPath, String id) { | |
client = CuratorFrameworkFactory.newClient(connString, new ExponentialBackoffRetry(1000, Integer.MAX_VALUE)); | |
this.id = id; | |
this.latchPath = latchPath; | |
} | |
public void start() throws Exception { | |
client.start(); | |
client.getZookeeperClient().blockUntilConnectedOrTimedOut(); | |
leaderLatch = new LeaderLatch(client, latchPath, id); | |
leaderLatch.start(); | |
} | |
public boolean isLeader() { | |
return leaderLatch.hasLeadership(); | |
} | |
public Participant currentLeader() throws Exception { | |
return leaderLatch.getLeader(); | |
} | |
public void close() throws IOException { | |
leaderLatch.close(); | |
client.close(); | |
} | |
public static void main(String[] args) throws Exception { | |
String latchPath = "/latch"; | |
String connStr = "10.12.136.235:2181"; | |
LeaderLatchExample node1 = new LeaderLatchExample(connStr, latchPath, "node-1"); | |
LeaderLatchExample node2 = new LeaderLatchExample(connStr, latchPath, "node-2"); | |
node1.start(); | |
node2.start(); | |
for (int i = 0; i < 10; i++) { | |
System.out.println("node-1 think the leader is " + node1.currentLeader()); | |
System.out.println("node-2 think the leader is " + node2.currentLeader()); | |
Thread.sleep(10000); | |
} | |
node1.close(); | |
System.out.println("now node-2 think the leader is " + node2.currentLeader()); | |
node2.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment