zookeeper 簡單的代碼demo
寫了一個關于zookeepeer應用的簡單demo
服務端定時的向zookeeper集群注冊,客戶端監聽zookeeper服務節點變化,一旦變化,立刻響應,更新服務端列表
服務端代碼:
#include <zookeeper/zookeeper.h> #include <zookeeper/zookeeper_log.h> #include <iostream> using namespace std; void InitWatch(zhandle_t* zh, int type, int state, const char* path, void* watcher) { if (type == ZOO_SESSION_EVENT) { if (state == ZOO_CONNECTED_STATE) { cout << "build connection ok" << endl; } else if (state == ZOO_EXPIRED_SESSION_STATE) { cout << "connection disconnect" << endl; } } } void CreateWatch(int rc, const char *name, const void *data) { if (rc == ZNODEEXISTS || rc == ZOK) { if (rc == ZOK) { cout << "registry ok" << endl; } else { cout << "node exist" << endl; } } else { cout << "registry error" << endl; } } int main(int argc, char* argv[]) { const char* host = "10.7.18.31:2181,10.7.18.199:2181"; int timeout = 100000; zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); zhandle_t* zkhandle = NULL; zkhandle = zookeeper_init(host, InitWatch, timeout, 0, const_cast<char*>("TODO"), 0); while (1) { if (!zkhandle) { zookeeper_close(zkhandle); zkhandle = zookeeper_init(host, InitWatch, timeout, 0, const_cast<char*>("TODO"), 0); } if (NULL == zkhandle) { cout << "zookeeper init error" << endl; sleep(1); continue; } int ret = zoo_acreate(zkhandle, "/cluster/index+endpoint", "", 8, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, CreateWatch, "create"); if (ret) { cout << "zoo_acreate error :" << ret << endl; } sleep(5); } zookeeper_close(zkhandle); }客戶端代碼:
#include <zookeeper/zookeeper.h> #include <zookeeper/zookeeper_log.h> #include <iostream> using namespace std; void InitWatch(zhandle_t* zh, int type, int state, const char* path, void* watcher) { if (type == ZOO_SESSION_EVENT) { if (state == ZOO_CONNECTED_STATE) { cout << "build connection ok" << endl; } else if (state == ZOO_EXPIRED_SESSION_STATE) { cout << "connection disconnect" << endl; } } } void CreateWatch(int rc, const char *name, const void *data) { if (rc == ZNODEEXISTS || rc == ZOK) { if (rc == ZOK) { cout << "registry ok" << endl; } else { cout << "node exist" << endl; } } else { cout << "registry error" << endl; } } int main(int argc, char* argv[]) { const char* host = "10.7.18.31:2181,10.7.18.199:2181"; int timeout = 100000; zoo_set_debug_level(ZOO_LOG_LEVEL_WARN); zhandle_t* zkhandle = NULL; zkhandle = zookeeper_init(host, InitWatch, timeout, 0, const_cast<char*>("TODO"), 0); while (1) { if (!zkhandle) { zookeeper_close(zkhandle); zkhandle = zookeeper_init(host, InitWatch, timeout, 0, const_cast<char*>("TODO"), 0); } if (NULL == zkhandle) { cout << "zookeeper init error" << endl; sleep(1); continue; } int ret = zoo_acreate(zkhandle, "/cluster/index+endpoint", "", 8, &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, CreateWatch, "create"); if (ret) { cout << "zoo_acreate error :" << ret << endl; } sleep(5); } zookeeper_close(zkhandle); }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!