zookeeper提供了nodejs客户端,下面代码则是使用nodejs客户端连接zookeeper
添加依赖
package.json中加入
"node-zookeeper-client": "^0.2.2"
建立连接
var zookeeper = require('node-zookeeper-client');
//zookeeper服务地址
var zk_url="127.0.0.1:2181";
var client = zookeeper.createClient(zk_url);
列出节点并获取节点数据
function listChildren(client, path) {
client.getChildren(
path,
function (event) {
console.log(event);
listChildren(client, path);
},
function (error, children, stat) {
if (error) {
console.log(children);
return;
}
if(children.length != 0){
for(var i in children){
client.getData(
path+"/"+children[i],
function (event) {
console.log('事件: %s.', event);
},
function (error, data, stat) {
if (error) {
console.log(error.stack);
return;
}
console.log('节点数据: %s', data.toString('utf8'));
}
);
}
}
}
);
}
开启连接,并在第一次连接的时候列举数据
var path="/test/hello"
client.once('connected', function () {
listChildren(client, path);
});
client.connect();