public class ZKConnector implements Watcher{
private static final Logger logger =LoggerFactory.getLogger(ZKConnector.class); private CountDownLatch connectedSemaphore = new CountDownLatch(1);
private ZooKeeper zk =null; /**
* 释放zookeeper连接
*/
public void releaseConnection() {
if (this.zk!=null) {
try {
this.zk.close();
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
} /**
* 创建zookeeper的连接
* @param connectString zookeeper服务器地址列表
* @param sessionTimeout Session超时时间
*/
public void createConnection(String connectString, int sessionTimeout) {
//先释放zookeeper连接
this.releaseConnection();
try {
zk = new ZooKeeper( connectString, sessionTimeout, this);
connectedSemaphore.await();
} catch ( InterruptedException e ) {
logger.info( "连接创建失败,发生 InterruptedException");
e.printStackTrace();
} catch (IOException e ) {
logger.info( "连接创建失败,发生 IOException" );
e.printStackTrace();
}
} /**
* 检查Znode是否为空
*/
public boolean check(String zNode){
try {
return this.zk.exists(zNode, false).getDataLength()>0;
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
return false;
} /**
* 检查zNode是否存在
* 不为空 返回true
* 为空,则返回false
*/
public boolean exist(String zNode){
try {
Stat stat =this.zk.exists(zNode, false);
return stat==null?false:true;
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
return true;
} /**
* 读取zNode的数据
*/
public String readData(String path){
try {
if(this.zk.exists(path, false) == null){
return "";
}
return new String( this.zk.getData(path, false, null));
} catch ( KeeperException e){
logger.info("读取数据失败,发生KeeperException,path: " + path);
e.printStackTrace();
return "";
} catch ( InterruptedException e){
logger.info("读取数据失败,发生 InterruptedException,path: " + path);
e.printStackTrace();
return "";
}
} /**
* 更新zNode的数据
*/
public boolean writeData(String path,String data){
try {
if(this.zk.exists(path, false) == null){
return createPersistNode(path,data);
}else{
deleteNode(path);
createPersistNode(path,data);
}
} catch ( KeeperException e ) {
logger.info( "更新数据失败,发生KeeperException,path: " + path );
e.printStackTrace();
} catch ( InterruptedException e ) {
logger.info( "更新数据失败,发生 InterruptedException,path: " + path );
e.printStackTrace();
}
return false;
} /**
* 获取子节点数据
*/
public List<String> getChildren(String node){
try {
List<String> subNodes = this.zk.getChildren(node, false);
return subNodes;
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
return null;
} /**
* 创建持久化节点
* @param path 节点path
* @param data 初始数据内容
* @return
*/
public boolean createPersistNode(String path, String data) {
try {
String createpath =this.zk.create(path,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT );
logger.info("节点创建成功, Path: "
+ createpath
+ ", content: " + data );
return true;
} catch ( KeeperException e ) {
logger.info( "节点创建失败,发生KeeperException" );
e.printStackTrace();
} catch ( InterruptedException e ) {
logger.info( "节点创建失败,发生 InterruptedException" );
e.printStackTrace();
}
return false;
} /**
* 创建短暂序列化节点
* @param path 节点path
* @param data 初始数据内容
* @param needWatch
* @return
*/
public String createEsquentialNode(String path, String data) {
String esquentialNode = null;
try {
esquentialNode =this.zk.create(path,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
logger.info("节点创建成功, Path: "
+ esquentialNode
+ ", content: " + data );
return esquentialNode;
} catch ( KeeperException e ) {
logger.info( "节点创建失败,发生KeeperException" );
e.printStackTrace();
} catch ( InterruptedException e ) {
logger.info( "节点创建失败,发生 InterruptedException" );
e.printStackTrace();
}
return null;
} /**
* 删除节点
*/
public void deleteNode(String path) {
try {
if(this.zk.exists(path, false) == null){
logger.info("该节点不存在!不做任何操作" );
}else{
this.zk.delete(path, -1);
logger.info("删除节点成功,path:"+ path);
}
} catch ( KeeperException e ) {
logger.info("删除节点失败,发生KeeperException,path: " + path);
e.printStackTrace();
} catch ( InterruptedException e ) {
logger.info("删除节点失败,发生 InterruptedException,path: " + path);
e.printStackTrace();
}
} @Override
public void process(WatchedEvent event) {
logger.info( "收到事件通知:" + event.getState() +"\n" );
if ( KeeperState.SyncConnected == event.getState() ) {
connectedSemaphore.countDown();
}
} }

连接Zookeeper操作的更多相关文章

  1. Zookeeper命令行操作(常用命令;客户端连接;查看znode路径;创建节点;获取znode数据,查看节点内容,设置节点内容,删除节点;监听znode事件;telnet连接zookeeper)

    8.1.常用命令 启动ZK服务 bin/zkServer.sh start 查看ZK服务状态 bin/zkServer.sh status 停止ZK服务 bin/zkServer.sh stop 重启 ...

  2. 第8章 ZooKeeper操作

    目录 8.1 集群环境搭建 1.上传ZooKeeper安装文件 2.编写配置文件 3.拷贝ZooKeeper安装信息到其它节点 4.修改其它节点配置 5.启动ZooKeeper 6.查看启动状态 7. ...

  3. java连接zookeeper服务器出现“KeeperErrorCode = ConnectionLoss for /test”

    昨天调试java连接zookeeper服务器,zookeeper搭建过程在这里不做赘述,在创建连接后,然后操作节点一直报异常 错误信息如下: Exception in thread "mai ...

  4. Zookeeper入门(七)之Java连接Zookeeper

    Java操作Zookeeper很简单,但是前提要把包导对. 关于Zookeeper的Linux环境搭建可以参考我的这篇博客:Linux环境下Zookeeper安装 下面进入正题: 一.导入依赖 < ...

  5. JAVA 连接 ZooKeeper之初体验

    Java连接Zookeeper 一.配置zk环境 本人使用的是虚拟机,创建了两台linux服务器(安装过程百度上很多) 准备zk的安装包,zookeeper-3.4.10.tar.gz,可在Apach ...

  6. dubbo连接zookeeper注册中心因为断网导致线程无限等待问题【转】

    最近维护的系统切换了网络环境,由联通换成了电信网络,因为某些过滤规则导致系统连不上zookeeper服务器(应用系统机器在深圳,网络为电信线路,zookeeper服务器在北京,网络为联通线路),因为我 ...

  7. Zookeeper操作

    Zookeeper操作 注意搭建: 1.集群规模不小于3个节点 2.服务器之间系统时间要保持一致 1.搭建步骤: 1.解压安装包 2.设置zookeeper环境变量 3.修改配置文件————zoo.c ...

  8. 使用spring连接及操作mongodb3.0

    前边有一篇记录过不使用spring,直接在java代码中连接和操作mongodb数据库,这里就紧随其后记录一下使用spring的情况下,在java中简单操作mongodb.   maven导包配置: ...

  9. python连接zookeeper的日志问题

    用python连接zookeeper时,在终端里,一直会有zookeeper的日志冒出来,这样会很烦. -- ::,:(: Exceeded deadline by 11ms 解决方法是在连接后设置一 ...

随机推荐

  1. PHP 如何在txt里查找包含某个字符串的那一行?

    <?php $handler=fopen("1.txt","r"); while(!feof($handler)) { $m = fgets($handl ...

  2. [错误解决]ubuntu 不在 sudoers 文件中。此事将被报告。

    跟据报错判断,ubuntu没有sudo权限,经过查询需要将ubuntu账户加入/etc/sudoers中 先切换到root权限 su 输入密码 修改/etc/sudoers配置 vim /etc/su ...

  3. XMLHttpRequest对象创建

    本文摘抄自:Ajax知识体系大梳理地址:http://louiszhai.github.io/2016/11/02/ajax/本文内容并不完整,请到原文阅读. if (window.XMLHttpRe ...

  4. Git详解之二 Git基础 转

    http://www.open-open.com/lib/view/open1328069733264.html Git 基础 读完本章你就能上手使用 Git 了.本章将介绍几个最基本的,也是最常用的 ...

  5. MySQL误操作后如何快速恢复数据?

    摘要: 利用binlog闪回误操作数据. 基本上每个跟数据库打交道的程序员(当然也可能是你同事)都会碰一个问题,MySQL误操作后如何快速回滚?比如,delete一张表,忘加限制条件,整张表没了.假如 ...

  6. post方式的数据抓取

    public static String sendPost(String url, String param) {        PrintWriter out = null;        Buff ...

  7. 【Luogu】P3320寻宝游戏(Splay)

    题目链接 其实这题用Set就完事了但我不会Set 智商-=inf 求虚树上所有边权和的两倍. 具体方式就是splay把所有在虚树上的点存一下,(按照DFS序排序的)每次插入/删除会更新前驱和它.后继和 ...

  8. PHP算法面试题目

    1.使用PHP描述冒泡排序和快速排序算法,对象可以是一个数组 //冒泡排序(数组排序) functionbubble_sort($array){       $count = count($array ...

  9. HDU 4514 湫湫系列故事——设计风景线(并查集+树形DP)

    湫湫系列故事——设计风景线 Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others) To ...

  10. [HAOI2018][bzoj5306] 染色 [容斥原理+NTT]

    题面 传送门 思路 这道题的核心在于"恰好有$k$种颜色占了恰好$s$个格子" 这些"恰好",引导我们去思考,怎么求出总的方案数呢? 分开考虑 考虑把恰好有$s ...