使用curator进行选举

xiaoxiao2021-02-28  97

前言

1.笔者在开发项目的过程中,碰到一种情况。只能进行一台机器的处理。类型这样的分布式问题,我们可以通过zookeeper实现选举master的功能。

2.大体思路。  选择一个根据节点,例如/master_select,多台机器同时向该节点创建一个子节点/master_select/lock,利用zookeeper的特性,最终只有一台机器能够创建成功,成功的那台就作为Master选举。  Curator也是基于这个思路,但是它将节点创建,事件监听和自动选举进行了封装,开发人员只需要简单的调用API即可实现Master选举。下面我我们通过一个实例开看看如何使用Curator实现Master选举功能。

3.实例代码

<dependency> <groupid>org.apache.curator</groupid> <artifactid>curator-recipes</artifactid> <version>2.12.0</version> </dependency> package cn.datek.test.zookeeper; import java.util.List; 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.LeaderSelectorListener; import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:beans/spring-context.xml" }) public class RecipesMasterSelect { //dubbo.registry.address private String zkurl; private String master_path="/curator_recipes_master_path"; @Test public void master() throws Exception{ CuratorFramework client = CuratorFrameworkFactory.builder().connectString("10.0.250.222:2181").retryPolicy(new ExponentialBackoffRetry(1000, 3)).build(); client.start(); /** * 该实例封装了所有Master选举相关的逻辑,包括所有和Zookeeper服务器交互的过程,其中Master_select代表一个Master选举的一个 * 根节点,表明本次Master选举都是在该节点下进行的。 * 在创建LeaderSelector实例的时候,还会传入一个监听器:LeaderSelectorListenerAdapter。这需要开发人员自行实现。Curator * 会在成功获取Master权利时候回调该监听器。 */ LeaderSelector leaderSelector = new LeaderSelector(client, master_path, new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework client) throws Exception { // TODO Auto-generated method stub System.out.println("成为Master角色"); Thread.sleep(3000); List<string> path = client.getChildren().forPath(master_path); System.out.println(path); System.out.println("完成Master操作,释放Master权利"); } @Override public void stateChanged(CuratorFramework arg0, ConnectionState arg1) { // TODO Auto-generated method stub } }); leaderSelector.autoRequeue(); leaderSelector.start(); Thread.sleep(Integer.MAX_VALUE); } } </string>

转载请注明原文地址: https://www.6miu.com/read-70046.html

最新回复(0)