百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
E

etcd-cpp-apiv3

> 编程语言
开源

etcd-cpp-apiv3 是一个用于 etcd v3 客户端 API(即 ETCDCTL_API=3)的 C++ 库。

389 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

etcd-cpp-apiv3 是一个用于 etcd v3 客户端 API(即 ETCDCTL_API=3)的 C++ 库。

etcd-cpp-apiv3

The etcd-cpp-apiv3 is a C++ API for etcd's v3 client API, i.e., ETCDCTL_API=3.

Supported OS environments

  • Linux

    • Ubuntu 18.04, requires upgrade gRPC libraries (tested with 1.27.x).
    • Ubuntu 20.04
    • CentOS 8 (tested with 1.27.x)
  • MacOS

    • MacOS 10.15
    • MacOS 11.0
  • Windows

    • Windows 10, with vcpkg

Supported etcd versions:

  • etcd 3.2, tested with v3.2.26
  • etcd 3.3, tested with v3.3.11
  • etcd 3.4, tested with v3.4.13

Requirements

  1. boost and openssl (Note that boost is only required if you need the asynchronous runtime)

    • On Ubuntu, above requirement could be installed as:

      apt-get install libboost-all-dev libssl-dev
      
    • On MacOS, above requirement could be installed as:

      bash
      brew install boost openssl
  2. protobuf & gRPC

    • On Ubuntu, above requirements related to protobuf and gRPC can be installed as:

      bash
      apt-get install libgrpc-dev \
              libgrpc++-dev \
              libprotobuf-dev \
              protobuf-compiler-grpc
      
    • On MacOS, above requirements related to protobuf and gRPC can be installed as:

      bash
      brew install grpc protobuf
      
    • When building grpc from source code (e.g., on Ubuntu 18.04 and on CentOS), if the system-installed openssl is preferred, you need to add -DgRPC_SSL_PROVIDER=package when building gRPC with CMake.

  3. cpprestsdk, the latest version of master branch on github should work, you can build and install this dependency using cmake with:

    bash
     git clone https://github.com/microsoft/cpprestsdk.git
     cd cpprestsdk
     mkdir build && cd build
     cmake .. -DCPPREST_EXCLUDE_WEBSOCKETS=ON
     make -j$(nproc) && make install

API documentation

The etcd-cpp-apiv3 doesn't maintain a website for documentation, for detail usage of the etcd APIs, please refer to the "etcd operations" section in README, and see the detail C++ interfaces in Client.hpp and SyncClient.hpp.

Build and install

The etcd-cpp-apiv3 library could be easily built and installed using cmake, after all above dependencies have been successfully installed:

bash
git clone https://github.com/etcd-cpp-apiv3/etcd-cpp-apiv3.git
cd etcd-cpp-apiv3
mkdir build && cd build
cmake ..
make -j$(nproc) && make install

Using this package in your CMake project

To use this package in your CMake project, you can either

  • install, then find the library using find_package():

    cmake
    find_package(etcd-cpp-apiv3 REQUIRED)
    target_link_libraries(your_target PRIVATE etcd-cpp-api)
  • or, add this repository as a subdirectory in your project, and link the library directly:

    cmake
    add_subdirectory(thirdparty/etcd-cpp-apiv3)
    target_link_libraries(your_target PRIVATE etcd-cpp-api)
  • or, use FetchContent:

    cmake
    include(FetchContent)
    FetchContent_Declare(
      etcd-cpp-apiv3
      https://github.com/etcd-cpp-apiv3/etcd-cpp-apiv3.git
    )
    FetchContent_MakeAvailable(etcd-cpp-apiv3)
    target_link_libraries(your_target PRIVATE etcd-cpp-api)

Compatible etcd version

The etcd-cpp-apiv3 should work well with etcd > 3.0. Feel free to issue an issue to us on Github when you encounter problems when working with etcd 3.x releases.

Sync vs. Async runtime

There are various discussion about whether to support a user-transparent multi-thread executor in the background, or, leaving the burden of thread management to the user (e.g., see issue#100 and issue#207 for more discussion about the implementation of underlying thread model).

The etcd-cpp-apiv3 library supports both synchronous and asynchronous runtime, controlled by the cmake option BUILD_ETCD_CORE_ONLY=ON/OFF (defaults to OFF).

  • When it is set as OFF: the library artifact name will be libetcd-cpp-api.{a,so,dylib,lib,dll} and a cmake target etcd-cpp-api is exported and pointed to it. The library provides both synchronous runtime (etcd/SyncClient.hpp) and asynchronous runtime (etcd/Client.hpp), and the cpprestsdk is a required dependency.
  • When it is set as ON: the library artifact name will be libetcd-cpp-api-core.{a,so,dylib,lib,dll} and a cmake target etcd-cpp-api is exported and pointed to it. The library provides only the synchronous runtime (etcd/SyncClient.hpp), and the cpprestsdk won't be required.

We encourage the users to use the asynchronous runtime by default, as it provides more flexibility and convenient APIs and less possibilities for errors that block the main thread. Note that the asynchronous runtime requires cpprestsdk and will setup a thread pool in the background.

Warning: users cannot link both libetcd-cpp-api.{a,so,dylib,lib,dll} and libetcd-cpp-api-core.{a,so,dylib,lib,dll} to same program.

Usage

cpp
  etcd::Client etcd("http://127.0.0.1:2379");
  etcd::Response response = etcd.get("/test/key1").get();
  std::cout  response_task = etcd.get("/test/key1");
  // ... do something else
  etcd::Response response = response_task.get();
  std::cout `. You should
probably use a C++ lambda function here as a callback.

```c++
  etcd::Client etcd("http://127.0.0.1:2379");
  etcd.get("/test/key1").then([](etcd::Response response)
  {
    std::cout `. In the latter case you can get the actual `etcd::Response`
object with the `get()` function of the task. Calling get can raise exceptions so this is the way
how you can catch the errors generated by the REST interface. The `get()` call will not block in
this case since the response has been already arrived (we are inside the callback).

```c++
  etcd::Client etcd("http://127.0.0.1:2379");
  etcd.get("/test/key1").then([](pplx::task response_task)
  {
    try
    {
      etcd::Response response = response_task.get(); // can throw
      std::cout 
  void set_grpc_timeout(std::chrono::duration const &timeout)

Any std::chrono::duration value can be used to set the grpc timeout, e.g.,

cpp
  etcd.set_grpc_timeout(std::chrono::seconds(5));

Note that the timeout value is the "timeout" when waiting for responses upon the gRPC channel, i.e., CompletionQueue::AsyncNext. It doesn't means the timeout between issuing a .set() method getting the etcd::Response, as in the async mode the such a time duration is unpredictable and the gRPC timeout should be enough to avoid deadly waiting (e.g., waiting for a lock()).

Error code in responses

The class etcd::Response may yield an error code and error message when error occurs,

cpp
  int error_code() const;
  std::string const & error_message() const;

  bool is_ok() const;

The error code would be 0 when succeed, otherwise the error code might be

…

Etcd operations

Reading a value

You can read a value with the get() method of the client instance. The only parameter is the key to be read. If the read operation is successful then the value of the key can be acquired with the value() method of the response. Success of the operation can be checked with the is_ok() method of the response. In case of an error, the error_code() and error_message() methods can be called for some further detail.

Please note that there can be two kind of error situations. There can be some problem with the communication between the client and the etcd server. In this case the `get()``` method of the response task will throw an exception as shown above. If the communication is ok but there is some problem with the content of the actual operation, like attempting to read a non-existing key then the response object will give you all the details. Let's see this in an example.

The Value object of the response also holds some extra information besides the string value of the key. You can also get the index number of the creation and the last modification of this key with the created_index() and the modified_index() methods.

cpp
  etcd::Client etcd("http://127.0.0.1:2379");
  pplx::task response_task = etcd.get("/test/key1");

  try
  {
    etcd::Response response = response_task.get(); // can throw
    if (response.is_ok())
      std::cout  response_task = etcd.put("foo", "bar");

Modifying a value

Setting the value of a key can be done with the set() method of the client. You simply pass the key and the value as string parameters and you are done. The newly set value object can be asked from the response object exactly the same way as in case of the reading (with the value() method). This way you can check for example the index value of your modification. You can also check what was the previous value that this operation was overwritten. You can do that with the prev_value() method of the response object.

cpp
  etcd::Client etcd("http://127.0.0.1:2379");
  pplx::task response_task = etcd.set("/test/key1", "42");

  try
  {
    etcd::Response response = response_task.get();
    if (response.is_ok())
      std::cout  resp_task)
  {
    try
    {
      etcd::Response resp = resp_task.get();
      index = resp.index();
      std::cout  callback,
                        std::shared_ptr& watcher) {
  etcd::Client client(endpoints);
  wait_for_connection(client);

  // Check if the failed one has been cancelled first
  if (watcher && watcher->Cancelled()) {
    std::cout Wait([endpoints, prefix, callback,
    /* By reference for renewing */ &watcher](bool cancelled) mutable {
    if (cancelled) {
      std::cout  callback = printResponse;
const std::string prefix = "/test/key";

// the watcher initialized in this way will auto re-connect to etcd
std::shared_ptr watcher;
initialize_watcher(endpoints, prefix, callback, watcher);

…

c++
  etcd::Client etcd("http://127.0.0.1:2379");
  etcd::Response resp = etcd.leasegrant(60).get();
  etcd.set("/test/key2", "bar", resp.value().lease());
  std::cout  keepalive = etcd.leasekeepalive(60).get();
  std::cout Lease();

The remaining time-to-live of a lease can be inspected by

cpp
  etcd::Response resp2 = etcd.leasetimetolive(resp.value().lease()).get();
  std::cout ` and the handler will be invoked
when exception occurs during keeping it alive.

Note that the handler will invoked in a separated thread, not the thread where the `KeepAlive` object
is constructed.

…


See full example of the usages of transaction APIs, please refer to [./tst/TransactionTest.cpp](./tst/TransactionTest.cpp),
for full list of the transaction operation APIs, see [./etcd/v3/Transaction.hpp](./etcd/v3/Transaction.hpp).

### Election API

Etcd v3's [election APIs](https://github.com/etcd-io/etcd/blob/main/server/etcdserver/api/v3election/v3electionpb/v3election.proto)
are supported via the following interfaces,

```c++
pplx::task campaign(std::string const &name, int64_t lease_id,
                              std::string const &value);

pplx::task proclaim(std::string const &name, int64_t lease_id,
                              std::string const &key, int64_t revision,
                              std::string const &value);

pplx::task leader(std::string const &

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C++

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言