可以使用docker-compose安装zookeeper:
1 2 3 4 5 6 7 8 9 10 11
| services: zoo1: image: confluentinc/cp-zookeeper:7.3.2 hostname: zoo1 container_name: zoo1 ports: - "2181:2181" environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_SERVER_ID: 1 ZOOKEEPER_SERVERS: zoo1:2888:3888
|
然后创建Node.js的zookeeper的客户端,对zookeeper节点进行读写。这里使用node-zookeeper-client作为客户端,也可以选择其他类型的库。首先创建node.js项目,然后安装:
npm install node-zookeeper-client
接下来编写数据写入部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| const ZooKeeper = require('node-zookeeper-client');
const host = 'localhost:2181'; // ZooKeeper 服务器地址 const path = '/my-watched-node'; // ZooKeeper 中的节点路径
const zk = ZooKeeper.createClient(host, { sessionTimeout: 5000 });
zk.connect(); // 更新节点数据 function updateData() { const newData = Buffer.from('新数据1'); zk.exists(path,function(error,stat){ if(stat){ zk.setData(path, newData,function (error, stat) { if (error) { console.error('Failed to update node.', error); } else { console.log('设置数据'); } }); }else{ zk.create(path, newData,function (error, stat) { if (error) { console.error('Failed to update node.', error); } else { console.log('创建节点'); } }); } }) }
updateData();
|
然后编写数据读取部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const ZooKeeper = require('node-zookeeper-client');
const host = 'localhost:2181'; // ZooKeeper 服务器地址 const path = '/my-watched-node'; // ZooKeeper 中的节点路径
const zk = ZooKeeper.createClient(host, { sessionTimeout: 5000 });
zk.once('connected', function () { console.log('Connected to ZooKeeper.'); });
zk.connect();
zk.getData( path, function (error,data,stat) { console.log(data.toString()); } );
|
还可以进行数据订阅:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| const ZooKeeper = require('node-zookeeper-client');
const host = 'localhost:2181'; // ZooKeeper 服务器地址 const path = '/my-watched-node'; // ZooKeeper 中的节点路径
const zk = ZooKeeper.createClient(host, { sessionTimeout: 5000 });
zk.once('connected', function () { console.log('Connected to ZooKeeper.'); // 订阅节点数据变化 zk.exists(path, function(event){ if(event.type===3){ zk.getData( path, function (error,data,stat) { console.log(data.toString()); } ); } console.log(event) }, function (error, stat) { if (error) { console.log(error.stack); return; } if (stat) { console.log('Node exists.'); } else { console.log('Node does not exist.'); } }); });
zk.connect();
|
需要注意,在网上搜索zookeeper nodejs的示例代码,很多不能使用,需要查看原始文档,由于github不稳定,可以在gitee的镜像中查看:https://gitee.com/caomu0o/node-zookeeper-client#example
在getData和getChildren中都可以增加watcher