Skip to content

Latest commit

 

History

History
408 lines (320 loc) · 11.9 KB

README_zh_CN.md

File metadata and controls

408 lines (320 loc) · 11.9 KB

Nacos-sdk-cpp

Nacos-sdk-cpp是nacos客戶端的C++版本,它支持服务发现和动态配置

Gitter License

快速开始

设置工程

下载工程源代码并且执行下述命令:

cd nacos-sdk-cpp
cmake .
make

将会产生一个libnacos-cli.so 和一个 nacos-cli.out

运行 ./nacos-cli.out 以执行客户端的所有testcase

运行 make install 将libnacos-cli安装到lib目录

注意: 你需要在本机运行一个nacos server,监听8848端口以完成所有测试 其中有个测试将会测试端点(endpoint)功能,所以你还需要在本机运行一个http服务器,在路径/endpoints/endpoint0提供下述内容:

127.0.0.1:8848

这些例子你都能在nacos-sdk-cpp/examples/找到

将libnacos-cli集成到你的工程

下面的例子说明了如何将库文件(.so) 集成到你的工程:

IntegratingIntoYourProject.cpp:

#include <iostream>
#include "Nacos.h"

using namespace std;
using namespace nacos;

int main() {
    Properties props;
    props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address
    NacosServiceFactory *factory = new NacosServiceFactory(props);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    ConfigService *n = factory->CreateConfigService();
    ResourceGuard <ConfigService> _serviceFactory(n);
    NacosString ss = "";
    try {
        ss = n->getConfig("k", NULLSTR, 1000);
    }
    catch (NacosException &e) {
        cout <<
             "Request failed with curl code:" << e.errorcode() << endl <<
             "Reason:" << e.what() << endl;
        return -1;
    }
    cout << ss << endl;

    return 0;
}

g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lnacos-cli -o integrated.out

在本机的8848端口启动一个nacos server, 并且运行 ./integrated.out

你将会看到:

SuccessfullyIntegrated

如果你使用静态库(.a)链接

假设.a文件和待编译文件在同一目录, 请执行下述命令:

g++ -I/usr/local/include/nacos/ IntegratingIntoYourProject.cpp -lcurl -lz -L. -lnacos-cli-static -o integrated.out

使用-lcurl -lz指定nacos客户端使用的curl和lz库

使用-L. -lnacos-cli-static引用当前目录下的libnacos-cli-static.a

配置

获取配置

getConfig.cpp:

#include <iostream>
#include "Nacos.h"

using namespace std;
using namespace nacos;

int main() {
    Properties props;
    props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//Server address
    NacosServiceFactory *factory = new NacosServiceFactory(props);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    ConfigService *n = factory->CreateConfigService();
    ResourceGuard <ConfigService> _serviceFactory(n);
    NacosString ss = "";
    try {
        ss = n->getConfig("k", NULLSTR, 1000);
    }
    catch (NacosException &e) {
        cout <<
             "Request failed with curl code:" << e.errorcode() << endl <<
             "Reason:" << e.what() << endl;
        return -1;
    }
    cout << ss << endl;

    return 0;
}

发布配置

setConfig.cpp:

#include <iostream>
#include "Nacos.h"

using namespace std;
using namespace nacos;

int main() {
    Properties props;
    props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";//server address
    NacosServiceFactory *factory = new NacosServiceFactory(props);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    ConfigService *n = factory->CreateConfigService();
    ResourceGuard <ConfigService> _serviceFactory(n);
    bool bSucc = false;
    NacosString ss = "";

    try {
        bSucc = n->publishConfig("Cfg_key", NULLSTR, "Cfg_val");
        int retry = 0;
        ss = n->getConfig("Cfg_key", NULLSTR, 1000);
        while (!(ss == "Cfg_val") && retry++ < 10) {
            ss = n->getConfig("Cfg_key", NULLSTR, 1000);
        }

        if (!(ss == "Cfg_val")) {
            throw NacosException(0, "getConfig() failed.");
        }
    }
    catch (NacosException &e) {
        cout <<
             "Request failed with curl code:" << e.errorcode() << endl <<
             "Reason:" << e.what() << endl;

        return -1;
    }
    cout << "Publishing Key:Cfg_key with value:Cfg_val result:" << bSucc << endl;

    return 0;
}

监听配置变化和取消监听

listenToKeys.cpp:

#include <iostream>
#include "Nacos.h"

using namespace std;
using namespace nacos;

class MyListener : public Listener {
private:
    int num;
public:
    MyListener(int num) {
        this->num = num;
    }

    void receiveConfigInfo(const NacosString &configInfo) {
        cout << "===================================" << endl;
        cout << "Watcher" << num << endl;
        cout << "Watched Key UPDATED:" << configInfo << endl;
        cout << "===================================" << endl;
    }
};

int main() {
    Properties props;
    props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";
    NacosServiceFactory *factory = new NacosServiceFactory(props);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    ConfigService *n = factory->CreateConfigService();
    ResourceGuard <ConfigService> _serviceFactory(n);

    MyListener *theListener = new MyListener(1);//You don't need to free it, since it will be deleted by the function removeListener
    n->addListener("dqid", NULLSTR, theListener);//All changes on the key dqid will be received by MyListener

    cout << "Input a character to continue" << endl;
    getchar();
    cout << "remove listener" << endl;
    n->removeListener("dqid", NULLSTR, theListener);//Cancel listening
    getchar();

    return 0;
}

命名服务

注册和反注册实例

registerInstances.cpp:

#include <iostream>
#include <unistd.h>
#include "Nacos.h"

using namespace std;
using namespace nacos;

int main() {
    Properties configProps;
    configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
    NacosServiceFactory *factory = new NacosServiceFactory(configProps);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    NamingService *namingSvc = factory->CreateNamingService();
    ResourceGuard <NamingService> _serviceFactory(namingSvc);
    Instance instance;
    instance.clusterName = "DefaultCluster";
    instance.ip = "127.0.0.1";
    instance.port = 2333;
    instance.instanceId = "1";
    instance.ephemeral = true;

    //Registers 5 services named TestNamingService1...5
    try {
        for (int i = 0; i < 5; i++) {
            NacosString serviceName = "TestNamingService" + NacosStringOps::valueOf(i);
            instance.port = 2000 + i;
            namingSvc->registerInstance(serviceName, instance);
        }
    }
    catch (NacosException &e) {
        cout << "encounter exception while registering service instance, raison:" << e.what() << endl;
        return -1;
    }
    sleep(30);
    try {
        for (int i = 0; i < 5; i++) {
            NacosString serviceName = "TestNamingService" + NacosStringOps::valueOf(i);

            namingSvc->deregisterInstance(serviceName, "127.0.0.1", 2000 + i);
            sleep(1);
        }
    }
    catch (NacosException &e) {
        cout << "encounter exception while registering service instance, raison:" << e.what() << endl;
        return -1;
    }
    sleep(30);

    return 0;
}

订阅和取消订阅服务

subscribeServices.cpp:

#include <iostream>
#include "Nacos.h"

using namespace std;
using namespace nacos;

class MyServiceListener : public EventListener {
private:
    int num;
public:
    MyServiceListener(int num) {
        this->num = num;
    }

    void receiveNamingInfo(const ServiceInfo &serviceInfo){
        cout << "===================================" << endl;
        cout << "Watcher: " << num << endl;
        cout << "Watched service UPDATED: " << serviceInfo.toInstanceString() << endl;
        cout << "===================================" << endl;

    }
};

int main() {
    Properties props;
    props[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1:8848";
    //Interval for poller to check the status of subscribed services(unit:Ms), 30000 by default
    //Here we set it to 5000 to see the output more quick
    props[PropertyKeyConst::SUBSCRIPTION_POLL_INTERVAL] = "5000";
    NacosServiceFactory *factory = new NacosServiceFactory(props);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    NamingService *n = factory->CreateNamingService();
    ResourceGuard <NamingService> _serviceFactory(n);

    n->subscribe("ss", new MyServiceListener(1));
    cout << "Press any key to register services" << endl;
    getchar();

    n->registerInstance("ss", "127.0.0.1", 33);
    n->registerInstance("ss", "127.0.0.1", 34);
    cout << "Press any key to deregister services" << endl;
    getchar();

    n->deregisterInstance("ss", "127.0.0.1", 33);
    n->deregisterInstance("ss", "127.0.0.1", 34);
    cout << "All instances Unregistered, press any key to finish testing" << endl;
    getchar();

    return 0;
}

获取某个服务的全部实例

getAllInstances.cpp:

#include <iostream>
#include <list>
#include "Nacos.h"

using namespace std;
using namespace nacos;

int main() {
    Properties configProps;
    configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
    NacosServiceFactory *factory = new NacosServiceFactory(configProps);
    ResourceGuard <NacosServiceFactory> _guardFactory(factory);
    NamingService *namingSvc = factory->CreateNamingService();
    ResourceGuard <NamingService> _guardService(namingSvc);

    list <Instance> instances = namingSvc->getAllInstances("TestNamingService1");
    cout << "getAllInstances from server:" << endl;
    for (list<Instance>::iterator it = instances.begin();
         it != instances.end(); it++) {
        cout << "Instance:" << it->toString() << endl;
    }

    return 0;
}

启用认证

如果你的服务器启设置了密码,在上述任意一个例子当中加入下述配置,即可启用用户名密码认证:

using namespace nacos;
......
    configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
    configProps[PropertyKeyConst::AUTH_USERNAME] = "username";
    configProps[PropertyKeyConst::AUTH_PASSWORD] = "password";
    NacosServiceFactory *factory = new NacosServiceFactory(configProps);
    ConfigService *n = factory->CreateConfigService();
    NamingService *namingSvc = factory->CreateNamingService();
......

启动SPAS鉴权

using namespace nacos;
......
    configProps[PropertyKeyConst::SERVER_ADDR] = "127.0.0.1";
    configProps[PropertyKeyConst::ACCESS_KEY] = "accessKey";
    configProps[PropertyKeyConst::SECRET_KEY] = "secretKey";
    NacosServiceFactory *factory = new NacosServiceFactory(configProps);
    ConfigService *n = factory->CreateConfigService();
    NamingService *namingSvc = factory->CreateNamingService();
......

支持的系统/编译器

操作系统/环境 编译器 测试版本
MacOS Darwin 19.6.0 x86_64 Clang Apple clang version 12.0.0 (clang-1200.0.26.2)
Windows 10 WSL GCC version 4.8.4
Windows 10 CYGWIN_NT-10.0 x86_64 GCC version 10.2.0 (GCC)
Ubuntu1~16.04.12 GCC version 5.4.0
CentOS GCC
Windows Visual C++ 计划中

关于Nacos

Nacos (官方网站: http://nacos.io) 是一个易用的动态服务发现、配置管理以及服务管理平台。它将助力您轻松建立云上原生应用和微服务。

在Nacos中,服务是一级公民. Nacos 支持几乎所有种类的服务,例如:

Dubbo/gRPC service

Spring Cloud RESTFul service

Kubernetes service.