c++ 使用zookeeper


zookeeper是一個分布式的关串,開源的分布式應(yīng)用程序協(xié)調(diào)程序赏淌,可以為分布式應(yīng)用提供一致性服務(wù)踩寇,包括:配置維護(hù)、域名服務(wù)六水、分布式同步俺孙、組服務(wù),一般我們常用的功能包括使用zookeeper進(jìn)行配置統(tǒng)一管理掷贾、master選舉睛榄、分布式鎖、服務(wù)器注冊和發(fā)現(xiàn)等

zookeeper 官方只提供了 c client api, 沒有c++的api想帅,為了使用更加的方便场靴,接口更加好用,筆者簡單對c client進(jìn)行了下封裝港准,使c++用戶用起來更方便

封裝好的cpp接口見 https://github.com/yandaren/zk_cpp
下面簡單介紹下旨剥,zk_cpp的一些函數(shù)接口

1. 一些靜態(tài)的函數(shù)

這些函數(shù)主要是全局作用范圍的

    /**
     * @brief get the errocode string
     */
    static const char*  error_string(int32_t rc);

    /** 
     * @brief state to string
     */
    static const char*  state_to_string(int32_t state);

    /** 
     * @brief set zookeeper client internal log level
     */
    static void         set_log_lvl(zoo_log_lvl lvl);

    /** 
     * @brief set the log stream
     */
    static void         set_log_stream(FILE* file);

2. 然后就是對節(jié)點(diǎn)的一些常規(guī)訪問操作接口

  • 創(chuàng)建節(jié)點(diǎn)
    zoo_rc      create_persistent_node(const char* path, const std::string& value, const std::vector<zoo_acl_t>& acl);
    zoo_rc      create_sequence_node(const char* path, const std::string& value, const std::vector<zoo_acl_t>& acl, std::string& returned_path_name);
    zoo_rc      create_ephemeral_node(const char* path, const std::string& value, const std::vector<zoo_acl_t>& acl);
    zoo_rc      create_sequance_ephemeral_node(const char* path, const std::string& value, const std::vector<zoo_acl_t>& acl, std::string& returned_path_name);
  • 設(shè)置節(jié)點(diǎn)的值
    zoo_rc      set_node(const char* path, const std::string& value, int32_t version);
  • 獲取節(jié)點(diǎn)的值
    zoo_rc      get_node(const char* path, std::string& out_value, zoo_state_t* info, bool watch);
  • 獲取節(jié)點(diǎn)的所有子節(jié)點(diǎn)
    zoo_rc      get_children(const char* path, std::vector<std::string>& children, bool watch);
  • 刪除節(jié)點(diǎn)
    zoo_rc      delete_node(const char* path, int32_t version);
  • 節(jié)點(diǎn)是否存在
    zoo_rc      exists_node(const char* path, zoo_state_t* info, bool watch);
  • 設(shè)置節(jié)點(diǎn)的acl
    zoo_rc      set_acl(const char* path, const std::vector<zoo_acl_t>& acl, int32_t version);
  • 獲取節(jié)點(diǎn)的acl
    zoo_rc      get_acl(const char* path, std::vector<zoo_acl_t>& acl);
  • 添加權(quán)限認(rèn)證
    zoo_rc      add_auth(const std::string& user_name, const std::string& user_passwd);

3. 設(shè)置一些事件回調(diào)

  • 設(shè)置節(jié)點(diǎn)的值變化的通知回調(diào)函數(shù)
    zoo_rc      watch_data_change(const char* path, const data_change_event_handler_t& handler, std::string* value);
  • 設(shè)置節(jié)點(diǎn)的子節(jié)點(diǎn)變化(增/減)的通知回調(diào)函數(shù)
    zoo_rc      watch_children_event(const char* path, const child_event_handler_t& handler, std::vector<std::string>* out_children );

4. 具體的使用見zk_cpp_test.cpp

#include "zk_cpp/zk_cpp.h"
#include <stdio.h>
#include <iostream>
#include <string>

namespace utils {
    static std::string perms_to_string(int32_t perms) {
        if (perms == utility::zoo_perm_all) {
            return "all";
        }

        std::string ret;
        if (perms & utility::zoo_perm_create) {
            ret.append("c");
        }
        if (perms & utility::zoo_perm_read) {
            ret.append("r");
        }
        if (perms & utility::zoo_perm_delete) {
            ret.append("d");
        }
        if (perms & utility::zoo_perm_write) {
            ret.append("w");
        }
        if (perms & utility::zoo_perm_admin) {
            ret.append("a");
        }
        return ret;
    }

    static int32_t perms_string_to_int(const std::string& perm_str) {
        if (perm_str == "all") {
            return utility::zoo_perm_all;
        }

        int32_t perms = 0;
        for (auto c : perm_str) {
            if (c == 'c') {
                perms |= utility::zoo_perm_create;
            }
            else if (c == 'r') {
                perms |= utility::zoo_perm_read;
            }
            else if (c == 'd') {
                perms |= utility::zoo_perm_delete;
            }
            else if (c == 'w') {
                perms |= utility::zoo_perm_write;
            }
            else if (c == 'a') {
                perms |= utility::zoo_perm_admin;
            }
        }
        return perms;
    }

    static void        string_splits(const char* in_str, const char* sep_str, std::vector<std::string>& out_splits){
        std::string in(in_str);
        std::string sep(sep_str);
        std::size_t start_pos = 0;
        while (start_pos < in.size()){
            std::size_t pos = in.find(sep, start_pos);
            if (pos != std::string::npos){
                out_splits.push_back(std::move(in.substr(start_pos, pos - start_pos)));
                start_pos = pos + 1;
            }
            else{
                out_splits.push_back(std::move(in.substr(start_pos, in.size() - start_pos)));
                break;
            }
        }
    }
}

void print_zk_cpp_usage() {
    fprintf(stderr, "usage\n");
    fprintf(stderr, "    create <path> <value> <flag>\n"
                    "                          0 - persistence\n"
                    "                          1 - ephemeral \n"
                    "                          2 - sequence \n"
                    "                          3 - sequence and ephemeral\n");
    fprintf(stderr, "    delete <path>\n");
    fprintf(stderr, "    set <path> <data>\n");
    fprintf(stderr, "    get <path>\n");
    fprintf(stderr, "    ls <path>\n");
    fprintf(stderr, "    exists <path>\n");
    fprintf(stderr, "    setacl <path> scheme:id:perm\n");
    fprintf(stderr, "    getacl <path>\n");
    fprintf(stderr, "    addauth username passwd\n");
    fprintf(stderr, "    watch_data <path> \n");
    fprintf(stderr, "    watch_child <path> \n");
}

void data_change_event(const std::string& path, const std::string& new_value) {
    printf("data_change_event, path[%s] new_data[%s]\n", path.c_str(), new_value.c_str());
}

void child_change_events(const std::string& path, const std::vector<std::string>& children) {
    printf("child_change_events, path[%s] new_child_count[%d]\n", path.c_str(), (int32_t)children.size());

    for (int32_t i = 0; i < (int32_t)children.size(); ++i) {
        printf("%d, %s\n", i, children[i].c_str());
    }
}

int main() {
    printf("zk_cpp test\n");

    /** format is "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002" */
    std::string urls;

    printf("url formt is '127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002'\n");
    printf("input zk server urls:\n");
    std::cin >> urls;

    utility::zk_cpp zk;
    
    do {
        utility::zoo_rc ret = zk.connect(urls);
        if (ret != utility::z_ok) {
            printf("try connect zk server failed, code[%d][%s]\n", 
                ret, utility::zk_cpp::error_string(ret));
            break;
        }

        print_zk_cpp_usage();

        std::string cmd;
        while (std::cin >> cmd) {
            if (cmd == "create") {
                std::string path, value;
                int32_t flag;

                std::cin >> path >> value >> flag;

                std::string rpath = path;
                utility::zoo_rc ret = utility::z_ok;
                if (flag == 0) {
                    std::vector<utility::zoo_acl_t> acl;
                    acl.push_back(utility::zk_cpp::create_world_acl(utility::zoo_perm_all));
                    ret = zk.create_persistent_node(path.c_str(), value, acl);
                }
                else if (flag == 1) {
                    std::vector<utility::zoo_acl_t> acl;
                    acl.push_back(utility::zk_cpp::create_world_acl(utility::zoo_perm_all));
                    ret = zk.create_ephemeral_node(path.c_str(), value, acl);
                }
                else if (flag == 2) {
                    std::vector<utility::zoo_acl_t> acl;
                    acl.push_back(utility::zk_cpp::create_world_acl(utility::zoo_perm_all));
                    ret = zk.create_sequence_node(path.c_str(), value, acl, rpath);
                }
                else if (flag == 3) {
                    std::vector<utility::zoo_acl_t> acl;
                    acl.push_back(utility::zk_cpp::create_world_acl(utility::zoo_perm_all));
                    ret = zk.create_sequance_ephemeral_node(path.c_str(), value, acl, rpath);
                }
                else {
                    printf("invalid create path flag[%d]\n", flag);
                    continue;
                }

                printf("create path[%s] flag[%d] ret[%d][%s], rpath[%s]\n",
                    path.c_str(), flag, ret, utility::zk_cpp::error_string(ret), rpath.c_str());
            }
            else if (cmd == "get") {
                std::string path;
                std::string value;

                std::cin >> path;

                utility::zoo_rc ret = zk.get_node(path.c_str(), value, nullptr, true);
                printf("try get path[%s]'s value, value[%s] ret[%d][%s]\n",
                    path.c_str(), value.c_str(), ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "set") {
                std::string path;
                std::string value;

                std::cin >> path >> value;

                utility::zoo_rc ret = zk.set_node(path.c_str(), value, -1);
                printf("try set path[%s]'s value to [%s] ret[%d][%s]\n",
                    path.c_str(), value.c_str(), ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "exist") {
                std::string path;

                std::cin >> path;

                utility::zoo_rc ret = zk.exists_node(path.c_str(), nullptr, true);
                printf("try_check path[%s] exist[%d], ret[%d][%s]\n",
                    path.c_str(), ret == utility::z_ok, ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "ls") {
                std::string path;
                std::vector<std::string> children;

                std::cin >> path;

                utility::zoo_rc ret = zk.get_children(path.c_str(), children, true);
                printf("try get path[%s]'s children's, children count[%d], ret[%d][%s]\n",
                    path.c_str(), (int32_t)children.size(), ret, utility::zk_cpp::error_string(ret));

                std::string list;
                list.append("[");

                for (int32_t i = 0; i < (int32_t)children.size(); ++i) {
                    //printf("%s\n", children[i].c_str());
                    list.append(children[i]).append(", ");
                }

                list.append("]");
                printf("%s\n", list.c_str());
            }
            else if (cmd == "delete") {
                std::string path;

                std::cin >> path;

                utility::zoo_rc ret = zk.delete_node(path.c_str(), -1);
                printf("try delete path[%s], ret[%d][%s]\n",
                    path.c_str(), ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "setacl") {
                /* setacl <path> scheme:id:perm */
                std::string path;
                std::string acl_string;

                std::cin >> path >> acl_string;

                std::vector<std::string> splits;

                utils::string_splits(acl_string.c_str(), ":", splits);

                if (splits.size() < 3) {
                    printf("acl formt[%s] error\n", acl_string.c_str());
                    continue;
                }
                std::vector<utility::zoo_acl_t> acl;

                const std::string& scheme = splits[0];
                int32_t perms = 0; 
                if (scheme == "world") {
                    const std::string& id = splits[1];
                    if (id != "anyone") {
                        printf("acl world formt error, id[%s]\n", id.c_str());
                        continue;
                    }
                    const std::string& perm_str = splits[2];
                    perms = utils::perms_string_to_int(perm_str);

                    auto ac = utility::zk_cpp::create_world_acl(perms);
                    acl.push_back(ac);
                }
                else if (scheme == "auth") {
                    // "id" is empty
                    const std::string& perm_str = splits[2];
                    perms = utils::perms_string_to_int(perm_str);

                    auto ac = utility::zk_cpp::create_auth_acl(perms);
                    acl.push_back(ac);
                }
                else if (scheme == "digest") {
                    if (splits.size() < 4) {
                        printf("acl digest formt error, acl_str[%s]\n", acl_string.c_str());
                        continue;
                    }

                    const std::string& user_name = splits[1];
                    const std::string& passwd = splits[2];
                    const std::string& perm_str = splits[3];
                    perms = utils::perms_string_to_int(perm_str);

                    auto ac = utility::zk_cpp::create_digest_acl(perms, user_name, passwd);
                    acl.push_back(ac);
                }
                else if (scheme == "ip") {
                    const std::string& id = splits[1];
                    const std::string& perm_str = splits[2];
                    perms = utils::perms_string_to_int(perm_str);
                    auto ac = utility::zk_cpp::create_ip_acl(perms, id);
                    acl.push_back(ac);
                }
                else {
                    printf("unsupported scheme[%s]\n", scheme.c_str());
                    continue;
                }

                auto ret = zk.set_acl(path.c_str(), acl, -1);
                printf("set acl for path[%s], ret[%d][%s]\n", path.c_str(), ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "getacl") {
                std::string path;
                std::cin >> path;

                std::vector<utility::zoo_acl_t> acl;
                utility::zoo_rc rt = zk.get_acl(path.c_str(), acl);
                printf("get acl of path[%s], ret[%d][%s], acl_count[%d]\n",
                    path.c_str(), ret, utility::zk_cpp::error_string(ret), (int32_t)acl.size());

                for (auto& ac : acl) {
                    printf("%s:%s:%s\n", ac.scheme.c_str(), ac.id.c_str(), utils::perms_to_string(ac.perm).c_str());
                }
            }
            else if (cmd == "addauth") {
                std::string user_name;
                std::string user_passwd;
                std::cin >> user_name >> user_passwd;

                utility::zoo_rc rt = zk.add_auth(user_name, user_passwd);
                printf("add_auth, ret[%d][%s].\n", ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "watch_data") {
                std::string path;

                std::cin >> path;
                std::string value;

                utility::zoo_rc ret = zk.watch_data_change(path.c_str(), data_change_event, &value);

                printf("try watch_data change of path[%s], value[%s] ret[%d][%s]\n",
                    path.c_str(), value.c_str(), ret, utility::zk_cpp::error_string(ret));
            }
            else if (cmd == "watch_child") {
                std::string path;
                std::cin >> path;

                std::vector<std::string> children;

                utility::zoo_rc ret = zk.watch_children_event(path.c_str(), child_change_events, &children);

                printf("try watch_child change of path[%s], child_count[%d] ret[%d][%s]\n",
                    path.c_str(), (int32_t)children.size(), ret, utility::zk_cpp::error_string(ret));

                for (int32_t i = 0; i < (int32_t)children.size(); ++i) {
                    printf("%d, %s\n", i, children[i].c_str());
                }
            }
            else {
                printf("unsupported msg[%s]\n", cmd.c_str());
            }
        }

    } while (0);

#ifdef _WIN32
    system("pause");
#endif

    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市浅缸,隨后出現(xiàn)的幾起案子轨帜,更是在濱河造成了極大的恐慌,老刑警劉巖衩椒,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蚌父,死亡現(xiàn)場離奇詭異,居然都是意外死亡烟具,警方通過查閱死者的電腦和手機(jī)梢什,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來朝聋,“玉大人嗡午,你說我怎么就攤上這事〖胶郏” “怎么了荔睹?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長言蛇。 經(jīng)常有香客問我僻他,道長,這世上最難降的妖魔是什么腊尚? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任吨拗,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘劝篷。我一直安慰自己哨鸭,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布娇妓。 她就那樣靜靜地躺著像鸡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哈恰。 梳的紋絲不亂的頭發(fā)上只估,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天,我揣著相機(jī)與錄音着绷,去河邊找鬼蛔钙。 笑死,一個胖子當(dāng)著我的面吹牛荠医,可吹牛的內(nèi)容都是我干的夸楣。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼子漩,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了石洗?” 一聲冷哼從身側(cè)響起幢泼,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎讲衫,沒想到半個月后缕棵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡涉兽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年招驴,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片枷畏。...
    茶點(diǎn)故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡别厘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出拥诡,到底是詐尸還是另有隱情触趴,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布渴肉,位于F島的核電站冗懦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏仇祭。R本人自食惡果不足惜披蕉,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧没讲,春花似錦眯娱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至贰谣,卻和暖如春娜搂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背吱抚。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工百宇, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人秘豹。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓携御,卻偏偏與公主長得像,于是被迫代替她去往敵國和親既绕。 傳聞我的和親對象是個殘疾皇子啄刹,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評論 2 354