本篇内容主要讲解“zookeeper的选举法怎么用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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(); } }
到此,相信大家对“zookeeper的选举法怎么用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。