用C实现了一个zkclient,读取指定的节点值
编译库
下载解压zk源码
cd zookeeper-3.5.4-beta/src/c
make
生成两个静态库
libzookeeper_mt.la
libzookeeper_st.la
添加库
Makefile文件中添加静态库
LIBS += -L../lib -Bstatic -lzookeeper_mt -lzookeeper_st
源码
int doReadNode(const char* pathName, const char* childNodeName){
int rc = 0;
char path[256];
if (NULL != childNodeName)
{
sprintf(path, "%s/%s", pathName, childNodeName);
}
if (strstr(path, CFG_ITEM_VALUE))
{
rc=zoo_aget(zh, path,1,readCompletion, NULL);
if (rc!=ZOK)
{
logError("[ZKCLIENT] Read remoteip error !\n");
}
}
zoo_wexists(zh, path , watcher, (void*) 0, NULL);
return rc;
}
void watcher(zhandle_t *zzh, int type, int state, const char *path,
void* context)
{
if (type == ZOO_SESSION_EVENT) {
if (state == ZOO_CONNECTED_STATE) {
//连接后,将所有节点全部读取一次
doReadNodes();
} else if (state == ZOO_AUTH_FAILED_STATE) {
zookeeper_close(zzh);
zh=NULL;
} else if (state == ZOO_EXPIRED_SESSION_STATE) {
zookeeper_close(zzh);
zh=NULL;
}
else{
printf("[ZKCLIENT] Watcher state = %d\n", state);
}
}
else if ((type == ZOO_CHANGED_EVENT)
|| (type == ZOO_CREATED_EVENT)){
doReadNode(path, NULL);
}
else if (type == ZOO_DELETED_EVENT)
{
doReadNode(path, NULL);
}
else
{
printf("[ZKCLIENT] Watcher state = %d\n", state);
}
}
bool zkConnect(const char* host){
int rc = 0;
zh = zookeeper_init(host, watcher, 30000, 0, 0, 0);
if (NULL == zh){
printf("zookeeper init error\n");
return false;
}
if (zoo_state(zh)==ZOO_NOTCONNECTED_STATE) {
//zkClinetClose();
//return false;
}
return true;
}
int main(int argc, const char* argv[]) {
cfgFile_t cfg;
memset((void *)&cfg, 0, sizeof(cfg));
char host[256] = "10.47.228.30:2181/config/value";
while (true)
{
//连接ZK Server
if(zkConnect(host))
{
initCfg();
//将所有的节点都读取一遍
doReadNodes();
while(true)
{
if (!CheckZKConnect())
{
break;
}
//zk配置和本地配置对比,确认是否发生变化
if (checkCfgChange(&cfg))
{
//配置变动
}
sleep(3);
}
zkClinetClose();
}
else
{
sleep(10);
}
}
return true;
}