java连接zookeeper 用线程启动并监听节点
时间: 2024-03-20 15:45:23 浏览: 70
在Java中连接ZooKeeper,可以使用ZooKeeper提供的ZooKeeper类。要在线程中启动并监听节点,可以使用Java的多线程技术。
下面是一个简单的Java代码示例,用于连接ZooKeeper并在线程中启动并监听节点:
```java
import org.apache.zookeeper.*;
import java.io.IOException;
public class ZooKeeperThread implements Runnable, Watcher {
private ZooKeeper zooKeeper;
public ZooKeeperThread(String connectString, int sessionTimeout) throws IOException, KeeperException, InterruptedException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, this);
}
public void run() {
try {
// 创建一个节点,用于后面的演示
zooKeeper.create("/test", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// 监听节点
zooKeeper.getData("/test", this, null);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDataChanged) {
try {
byte[] data = zooKeeper.getData(event.getPath(), this, null);
System.out.println("Node data changed: " + new String(data));
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeperThread zooKeeperThread = new ZooKeeperThread("localhost:2181", 5000);
Thread thread = new Thread(zooKeeperThread);
thread.start();
thread.join();
}
}
```
在这个代码中,我们定义了一个ZooKeeperThread类,其中实现了Runnable和Watcher接口。在类的构造函数中,我们首先连接ZooKeeper。在run()方法中,我们创建了一个名为“/test”的节点,并监听该节点。在process()方法中,我们判断事件类型是否为“NodeDataChanged”,如果是,我们就获取节点的最新数据,并输出到控制台。在main()方法中,我们启动一个线程,并等待线程的结束。
当节点的数据发生变化时,程序将会输出一个消息,如下所示:
```
Node data changed: world
```
阅读全文