美文网首页
ZooKeeper应用场景:配置管理

ZooKeeper应用场景:配置管理

作者: RacyFu | 来源:发表于2019-09-28 12:40 被阅读0次

ZooKeeper可以统一修改集群中的配置信息,主要使用它的watcher功能。

下面表格列出了写操作与ZK内部产生的事件的对应关系:

而ZK内部的写事件与所触发的watcher的对应关系如下:

实现永久监听:

import org.apache.zookeeper.*;

import org.apache.zookeeper.data.Stat;

import java.io.IOException;

import java.util.concurrent.CountDownLatch;

public class ZooKeeperWatcherDemo {

static final String CONNECT_ADDR = "192.168.220.135:2181,192.168.220.136:2181,192.168.220.137:2181";

static final int SESSION_OUTTIME = 2000;//ms

/** * 阻塞程序执行,等待zookeeper连接成功 */

static final CountDownLatch connectedSemaphore = new CountDownLatch(1);

static final String PATH = "/configroot";

public static void main(String[] args) { try {

//连接 ZooKeeper zk = new ZooKeeper(CONNECT_ADDR, SESSION_OUTTIME, event -> {

System.out.println("事件是:"+event.getType());

//如果收到了服务端的响应事件,连接成功

if (Watcher.Event.KeeperState.SyncConnected == event.getState()) {

connectedSemaphore.countDown(); } });

connectedSemaphore.await();

System.out.println("连接成功!");

System.out.println(zk.getState());

zk.create(PATH, "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

//可以绑定事件的操作:getData、exists、getChildren // 通过exists绑定事件 //如果第二个参数为true,事件会触发至创建该ZooKeeper中的Watcher中 //Stat stat = zk.exists(PATH,true); //在当前exists中单独触发一个事件

Stat stat = zk.exists(PATH, event -> {

System.out.println(event.getType() + "--->" + event.getPath());

try { zk.exists(event.getPath(),true);  //在次触发事件

} catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } });  

//触发Watcher事件

Stat stat2 = zk.setData(PATH, "1".getBytes(), stat.getVersion());

Thread.sleep(1000);

zk.delete(PATH,stat2.getVersion());

zk.close();

} catch (IOException | InterruptedException | KeeperException e) { e.printStackTrace(); } }}

相关文章

  • ZooKeeper应用场景:配置管理

    ZooKeeper可以统一修改集群中的配置信息,主要使用它的watcher功能。 下面表格列出了写操作与ZK内部产...

  • zookeeper环境搭建及说明

    zk主要作用是协调数据。应用场景之一分布式配置管理。 下载软件http://zookeeper.apache.or...

  • ZooKeeper和Diamond有什么不同

    本文主要是讨论下两个类似产品:ZooKeeper和Diamond在配置管理这个应用场景上的异同点。 Diamond...

  • javaAPI操作zookeeper

    【前言】zookeeper应用的场景主要有四种:通知服务、配置管理、集群管理、分布式锁。其还有一最大的特点就是数据...

  • Zookeeper 基础知识

    Zookeeper是什么 Zookeeper 是一个高性能分布式应用协调服务Naming Service配置管理L...

  • ZooKeeper 安装

    ZooKeeper是一个高性能的分布式应用的协调服务,通过ZooKeeper提供的接口可以实现命名、配置管理、同步...

  • ZooKeeper应用场景及方案介绍

    本文主要从应用的角度对ZooKeeper做了浅析,试图阐明ZooKeeper是什么、主要应用场景有哪些、常用场景可...

  • 分布式专题(3)- Zookeeper

    什么是Zookeeper? 总结一句话,就是: ZooKeeper是一种分布式协调服务,可以实现分布式应用配置管理...

  • Zookeeper面试题锦集

    1、zookeeper是什么框架?zookeeper是一个开源的分布式协调服务框架。 2、有哪些应用场景?应用场景...

  • ZooKeeper高级特性

    1. ZooKeeper应用场景 ZooKeeper的应用场景主要包括:分布式协调,分布式锁,分布式元数据存储以及...

网友评论

      本文标题:ZooKeeper应用场景:配置管理

      本文链接:https://www.haomeiwen.com/subject/pczeyctx.html