com.ling.zookeeper.ZookeeperWatcher.java Source code

Java tutorial

Introduction

Here is the source code for com.ling.zookeeper.ZookeeperWatcher.java

Source

/*
 * Copyright 2005-2020 Daxia Team All rights reserved.
 * License: Daxia Team license
 */
package com.ling.zookeeper;

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZookeeperWatcher implements Watcher, Runnable {
    private ZooKeeper zk = null;
    private String znode;

    public ZooKeeper getZookeeper() {
        return zk;
    }

    public void connect(String hosts, String znode) throws IOException, KeeperException, InterruptedException {
        this.zk = new ZooKeeper(hosts, 2000, this);
        this.znode = znode;
        this.zk.exists(znode, true);
    }

    public void setData(String data) {
        try {
            Stat s = this.zk.exists(this.znode, true);
            this.zk.setData(this.znode, data.getBytes(), s.getVersion());
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println(event.toString());
        try {
            this.zk.exists(znode, true);//????????process
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            synchronized (this) {
                while (true) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}