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. [转载]用等高线图(Contour maps)可视化多变量函数

    https://blog.csdn.net/xlinsist/article/details/50920479 Overview 由于我们用手来画三维图像很困难,我们可以用等高线图来描述图像会更加简单 ...

  2. idea项目多模项目的搭建(复制)

    本文通过一个例子来介绍利用maven来构建一个多模块的jave项目.开发工具:intellij idea. 一.项目结构 multi-module-PRoject是主工程,里面包含两个模块(Modul ...

  3. HDU 4845 拯救大兵瑞恩(分层图状压BFS)

    拯救大兵瑞恩 Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others) Total Sub ...

  4. ssh(安全协议外壳)

    以下来源于百度百科 https://baike.baidu.com/item/ssh/10407?fr=aladdin SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Netw ...

  5. 【11】vue router 之导航钩子

    导航钩子 vue-router 提供的导航钩子主要用来拦截导航,让它完成跳转或取消.有多种方式可以在路由导航发生时执行钩子:全局的, 单个路由独享的, 或者组件级的.http://www.jiansh ...

  6. MacPro 系统空间竟占90G,如何清理--OmniDiskSweeper

    MacPro 经常提示我磁盘空间已满,管理磁盘空间. 然后我就管理了一下,发现系统竟占90个G,有点懵逼.然后网上查了资料,发现这个超级好用的工具OmniDiskSweeper. 打开是这样的! 然后 ...

  7. javascript获取querystring值【个人觉得这种方法最好最棒最像.NET】

    原文发布时间为:2009-05-22 -- 来源于本人的百度文章 [由搬家工具导入] JavaScript获取QueryString值, 当没有QueryString值时输出bool型 null 用j ...

  8. WIN8.1安装 .net framework 3.5

    1.虚拟光驱加载安装镜像 2.以管理员权限运行cmd 3.输入以下命令: dism.exe /online /enable-feature /featurename:NetFX3 /Source:X: ...

  9. 【Visual Studio】Visual Studio 2010 "LNK1123: 转换到 COFF 期间失败: 文件无效或损坏" 的解决方法

    1.将 项目|项目属性|配置属性|连接器|清单文件|嵌入清单 “是”改为“否”. 2.找到 C:\Windows\winsxs\x86_netfx-cvtres_for_vc_and_vb_b03f5 ...

  10. android的布局-----GridLayout(网格布局)

    学习导图 (一)简介 网格布局由GridLayout所代表,在android4.0之后新增加的布局管理器,因此需要android4.0之后的版本中使用,如果在更早的平台使用该布局管理器,则需要导入相应 ...