田雄兵 2014-03-03
zookeeper最经典的用法,选举。Curator的实现有2个种:
LeaderLatch:
这种是有阻塞的,就是大家一起上,谁先上了,就一直阻塞着,直到方法执行完成。如果执行结束,那么其他的兄弟就选一个出来。我觉得这种适合主备,比如开2 个 job,一个挂了另一个就上。
代码,这种代码最好是开2个eclipse看效果,顺序打开,看效果,再领悟:
package curator.selector; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderLatch; import org.apache.curator.retry.ExponentialBackoffRetry; public class LeaderLatchDemo { public static void main(String[] args) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(2000).connectionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("text").build(); client.start(); // 选举Leader 启动 LeaderLatch latch = new LeaderLatch(client,"/path"); latch.start(); latch.await(); System.err.println("我启动了"); Thread.currentThread().sleep(1000000); latch.close(); client.close(); } }
LeaderSelector:
这种复杂一点,他有个leaderSelector.autoRequeue();就是自动抢,比如打印一个helloworld,第一个打印完,第2个打印,然后第3个打印。然后第一个再打印,大家一起抢。有点动态选举的味道。
代码:
package curator.selector; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.leader.LeaderSelector; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.retry.ExponentialBackoffRetry; public class LeaderSelectorDemo { public static void main(String[] args) throws Exception { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").sessionTimeoutMs(5000).connectionTimeoutMs(10000).retryPolicy(retryPolicy).namespace("text").build(); client.start(); final LeaderSelector leaderSelector = new LeaderSelector(client, "/led", new LeaderSelectorListenerAdapter(){ @Override public void takeLeadership(CuratorFramework client) throws Exception { System.err.println("work ing..."); Thread.currentThread().sleep(3000); System.err.println("end"); } }); leaderSelector.autoRequeue(); leaderSelector.start(); System.in.read(); } }