Zookeeper实例Curator API-Master选举
2017-06-18 09:38
405 查看
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; /** * * @ClassName: Recipes_MasterSelect * @Description: TODO(这里用一句话描述这个类的作用) * @author RongShu * @date 2017年6月17日 下午1:52:31 * */ public class Recipes_MasterSelect { static String master_path = "/curator_recipes_master_path"; static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181") .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build(); public static void main(String[] args) throws Exception { client.start(); LeaderSelector selector = new LeaderSelector(client, master_path, new LeaderSelectorListenerAdapter() { public void takeLeadership(CuratorFramework client) throws Exception { System.out.println("成为Master角色"); Thread.sleep(3000); System.out.println("完成Master操作,释放Master权利"); } }); selector.autoRequeue(); selector.start(); Thread.sleep(Integer.MAX_VALUE); } } 输出 成为Master角色 完成Master操作,释放Master权利 成为Master角色 完成Master操作,释放Master权利 成为Master角色 完成Master操作,释放Master权利 成为Master角色 完成Master操作,释放Master权利 。。。。。
注意:
有这样一个需求:对于一个复杂的任务,仅需要从集群中选举出一台进行处理即可。借助Zookeeper,我们可以比较方便的实现Master选举功能,大体思路如下:
选择一个根节点,例如/master_select,多台机器同时向该节点创建一个子节点/master_select/lock,利用Zookeeper的特性,最终只有一台机器能够创建成功,成功的那台机器就作为Master,Curator也是这样的思路,但是它将节点的创建、事件的监听和自动选举的过程进行了封装,开发人员只需要调用API就可实现Master选举。
上面我们看到主要是创建了一个LeaderSelector实例,该实例负责封装所有和Master选举相关逻辑,包括所有和Zookeeper服务交互的过程,在创建LeaderSelector实例的时候,还会传入一个监听器:LeaderSelectorListenerAdapter,这需要开发人员自行实现,Curator会在成功获取到Master的时候回调该监听器中的takeLeadership方法,一旦该方法执行完毕,Curator会立刻放弃Master权利,开始新一轮的选举。
参考
1.《从Paxos到Zookeeper:分布式一致性原理与实践》
2. http://curator.apache.org/apidocs/index.html
相关文章推荐
- Zookeeper实例Curator API-使用Curator创建节点
- Zookeeper实例Curator API-NodeCache节点不存在实例
- Zookeeper实例Curator API-使用Curator删除节点
- Zookeeper实例Curator API-TestingCluster
- Zookeeper实例Curator API-使用Curator的异步接口
- Zookeeper实例Curator API-EnsurePath使用
- Zookeeper实例Curator API-PathChildrenCache_NoCacheData
- Zookeeper实例Curator API-使用Fluent风格的API接口来创建一个ZooKeeper客户端
- Zookeeper实例Curator API-NodeCache使用实例
- Zookeeper实例Curator API-分布式计数器
- Zookeeper实例Curator API-分布式Barrier
- Zookeeper开源客户端Curator之Master/Leader选举
- Zookeeper实例Curator API-分布式锁
- Zookeeper实例Curator API-PathChildrenCache
- Zookeeper实例Curator API-使用Curator更新数据内容
- Zookeeper实例Curator API-使用curator来创建一个含隔离命名空间的ZooKeeper客户端
- Zookeeper实例Curator API-使用curator来创建一个ZooKeeper客户端
- Zookeeper实例Curator API-TestingServer
- Distributed System: ZooKeeper系列之三 (Master选举和分布式锁)
- 使用zookeeper实现分布式master选举(c 接口版本)