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 与 Redis 入门教程

    Redis 官方推荐的 PHP 客户端是 Predis 和 phpredis. 前者是完全使用 PHP 代码实现的原生客户端,而后者则是使用 C 语言编写的 PHP 扩展.在功能上两者区别并不大,就性 ...

  2. Backpropagation Through Time (BPTT) 梯度消失与梯度爆炸

    Backpropagation Through Time (BPTT) 梯度消失与梯度爆炸 下面的图显示的是RNN的结果以及数据前向流动方向 假设有 \[ \begin{split} h_t & ...

  3. [oldboy-django][2深入django]老师管理--查看,添加,编辑

    # 添加老师(下拉框多选) 数据库设计: class Teacher(models.Model): name = models.CharField(max_length=64) cls = model ...

  4. Selenium - WebDriver: Waits

    These days most of the web apps are using AJAX techniques. When a page is loaded to browser, the ele ...

  5. VMSAv8-64 translation table format descriptors

    通常情况下,一个 descriptor 可能是以下的几种 entry: 非法或者异常的 entry. Table entry, 指向 next-level translation table. Blo ...

  6. [cocos2dx enhancement] CCPlatformMacros.h

    为了更好的调试Log,优化CCLOG格式 path: cocos2dx/platform/CCPlatformMacros.h line 218: #define CCLOGERROR(format, ...

  7. 【bzoj2946】[Poi2000]公共串 后缀自动机

    [Poi2000]公共串 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 1386  Solved: 620[Submit][Status][Discus ...

  8. response contentType

    response.setContentType(MIME)的作用是使客户端浏览器,区分不同种类的数据,并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据. 例如web浏览器就是通过MI ...

  9. pat 甲级 1099. Build A Binary Search Tree (30)

    1099. Build A Binary Search Tree (30) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN ...

  10. HDU4305 Lightning

    There are N robots standing on the ground (Don't know why. Don't know how). Suddenly the sky turns i ...