c++ 使用zookeeper


zookeeper是一个分布式的,开源的分布式应用程序协调程序,可以为分布式应用提供一致性服务,包括:配置维护、域名服务、分布式同步、组服务,一般我们常用的功能包括使用zookeeper进行配置统一管理、master选举、分布式锁、服务器注册和发现等

zookeeper 官方只提供了 c client api, 没有c++的api,为了使用更加的方便,接口更加好用,笔者简单对c client进行了下封装,使c++用户用起来更方便

封装好的cpp接口见 https://github.com/yandaren/zk_cpp
下面简单介绍下,zk_cpp的一些函数接口

1. 一些静态的函数

这些函数主要是全局作用范围的

    /**
     * @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. 然后就是对节点的一些常规访问操作接口

  • 创建节点
    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);
  • 设置节点的值
    zoo_rc      set_node(const char* path, const std::string& value, int32_t version);
  • 获取节点的值
    zoo_rc      get_node(const char* path, std::string& out_value, zoo_state_t* info, bool watch);
  • 获取节点的所有子节点
    zoo_rc      get_children(const char* path, std::vector<std::string>& children, bool watch);
  • 删除节点
    zoo_rc      delete_node(const char* path, int32_t version);
  • 节点是否存在
    zoo_rc      exists_node(const char* path, zoo_state_t* info, bool watch);
  • 设置节点的acl
    zoo_rc      set_acl(const char* path, const std::vector<zoo_acl_t>& acl, int32_t version);
  • 获取节点的acl
    zoo_rc      get_acl(const char* path, std::vector<zoo_acl_t>& acl);
  • 添加权限认证
    zoo_rc      add_auth(const std::string& user_name, const std::string& user_passwd);

3. 设置一些事件回调

  • 设置节点的值变化的通知回调函数
    zoo_rc      watch_data_change(const char* path, const data_change_event_handler_t& handler, std::string* value);
  • 设置节点的子节点变化(增/减)的通知回调函数
    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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270