• Stars
    star
    125
  • Rank 286,335 (Top 6 %)
  • Language
    C++
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

C++ client for Nacos

中文版本说明请点这里

Nacos-sdk-cpp

Nacos-sdk-cpp for c++ client allows users to access Nacos service, it supports service discovery and dynamic configuration.

Gitter License

Quick Examples

Setup project

Download the source and run the following command in bash:

cd nacos-sdk-cpp
cmake .
make

a libnacos-cli.so and a nacos-cli.out will be generated

run ./nacos-cli.out to perform test on the library

run make install to install the libnacos-cli to your system library path

Note: You need to run a nacos server on your local machine listening on port 8848 to go through the whole test One of the testcases will test endpoint functionality, so you also need to run a simple http server on port 80 which provides the following content:

127.0.0.1:8848

on path /nacos/endpoint0

All these examples could be found in nacos-sdk-cpp/examples/

Integrate the library into your project

Here is an example showing how to integrate the library(.so) into your project:

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

Start a nacos on your localmachine listening on port 8848, and run ./integrated.out

Then you'll see:

SuccessfullyIntegrated

If you are using a static lib(.a):

Assume that the file you are compiling resides in the same directory as the .a library, please use the following command:

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

-lcurl -lz Specifies the curl and lz library used by libnacos

-L. -lnacos-cli-static links the static libnacos library resides in the same directory as IntegratingIntoYourProject.cpp

Configuration

Get Config

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;
}

Publish Config

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;
}

Listen to key change & Cancel listening

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;
}

Naming

Register Instance & Unregister Instance

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;
}

Subscribe & Unsubscribe

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;
}

Get all instances of a service

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;
}

Enabling Authentication

If your Nacos server is secured with password, you can add the following snippet to any of the examples above to enable authentication:

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();
......

Enabling SPAS Authentication

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();
......

Supported System/Compilers

OS/Environment Compilers Tested version
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++ To be done

About Nacos

Nacos (official site: http://nacos.io) is an easy-to-use platform designed for dynamic service discovery and configuration and service management. It helps you to build cloud native applications and microservices platform easily.

Service is a first-class citizen in Nacos. Nacos supports almost all type of services, for example: Dubbo/gRPC service, Spring Cloud RESTFul service and Kubernetes service.

More Repositories

1

nacos-docker

This project contains a Docker image meant to facilitate the deployment of Nacos .
Shell
1,405
star
2

nacos-sdk-go

Nacos client in Golang
Go
1,123
star
3

nacos-examples

Nacos Examples
Java
953
star
4

r-nacos

Nacos server re-implemented in Rust.
Rust
812
star
5

nacos-spring-boot-project

Nacos ECO Project for Spring Boot
Java
785
star
6

nacos-spring-project

Nacos ECO Project for Spring Framework
Java
755
star
7

nacos-k8s

This project contains a Nacos Docker image meant to facilitate the deployment of Nacos on Kubernetes using StatefulSets.
Go
595
star
8

nacos-sdk-csharp

This nacos csharp sdk
C#
420
star
9

nacos-sdk-python

nacos python sdk
Python
373
star
10

nacos-sync

Service Sync component
Java
293
star
11

nacos-sdk-nodejs

nacos node.js sdk client
TypeScript
291
star
12

nacos-sdk-rust

nacos client for rust
Rust
123
star
13

grpc-java-registry-nacos

gRPC Nacos registry integration
Java
98
star
14

nacos-group.github.io

nacos-group.github.io
MDX
97
star
15

nacos-plugin

A collection of Nacos plug-ins, providing Nacos with pluggable plug-in capabilities, support for user customization and high scalability
Java
91
star
16

nacos-coredns-plugin

Nacos DNS-F Client Based On CoreDNS
Go
83
star
17

nacos-template

nacos-template include PPT template and knote
70
star
18

nginx-nacos-upstream

nginx nacos module. subscribe service and configuration from nacos instead of modifying and reloading nginx.conf
C
66
star
19

nacos-istio

Nacos integrate with Istio as a MCP server
Go
40
star
20

nacos-confd

Go
40
star
21

nacos-controller

nacos k8s controller
Go
25
star
22

dubbo-registry-nacos

Dubbo Registry support for Nacos
14
star
23

nacos-k8s-sync

A component for sync services between Nacos and Kubernetes.
Go
12
star
24

nacos-sdk-lua

Lua
12
star
25

nacos-activity

The documents presented in nacos activities
11
star
26

nacos-sdk-php

PHP
11
star
27

nacos-ctl

The controller command sdk for nacos
Java
7
star
28

logback-adapter

Java
5
star
29

acm2nacos-spring-cloud-example

Java
4
star
30

nacos-tutorial

Nacos 知行实验仓库
2
star
31

acm2nacos-java-example

Java
2
star
32

apollo-2-nacos-migration

Apollo迁移到Nacos的脚本工程
Java
1
star
33

nacos-logo

The logo files for nacos
1
star