問題現象
調用接口zookeeper_init()成功之後,使用句柄創建znode節點失敗。
問題分析
zookeeper_init()函數原型:
ZOOAPI zhandle_t *zookeeper_init(const char *host, watcher_fn fn,
int recv_timeout, const clientid_t *clientid, void *context, int flags);
在zookeeper.h頭文件中,對接口zookeeper_init()聲明時有如下注釋:
This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.
所以,僅僅通過判斷接口返回的句柄是否爲NULL,並不能表示句柄是可用的。因爲,會話的建立過程是異步的,必須等到會話狀態變成ZOO_CONNECTED_STATE才表示句柄可用。
問題解決方案
此問題解決方案有兩個:
- 通過zoo_state(zh)判斷句柄的狀態值是否爲ZOO_CONNECTED_STATE;
- Zookeeper的會話在建立成功後,會發送會話Watch事件,因此,可以通過Watch事件的type(ZOO_SESSION_EVENT)和state(ZOO_CONNECTED_STATE)來確認會話建立成功。