Develop C++ Apps

Prerequisites

The tutorial assumes that you have:

  • installed YugabyteDB, created a universe and are able to interact with it using the Redis shell. Ifnot please follow these steps in the Quick Start guide.
  • have C++11.

Installing the Redis C++ driver

We use the cpp_redis driver. To install the library do the following:

  • Clone the cpp_redis repository
  1. $ git clone https://github.com/Cylix/cpp_redis.git
  • Get the networking module (tacopie)
  1. $ cd cpp_redis
  2. $ git submodule init && git submodule update
  • Create a build directory and move into it
  1. $ mkdir build && cd build
  • Generate the Makefile using CMake
  1. $ cmake .. -DCMAKE_BUILD_TYPE=Release
  • Build and install the library
  1. $ make
  2. $ make install

Writing a hello world Redis application

Create a file ybredis_hello_world.cpp and copy the contents below:

  1. #include <cpp_redis/cpp_redis>
  2. #include<iostream>
  3. #include<vector>
  4. #include<string>
  5. #include<utility>
  6. using namespace std;
  7. int main() {
  8. cpp_redis::client client;
  9. client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
  10. if (status == cpp_redis::client::connect_state::dropped) {
  11. std::cout << "client disconnected from " << host << ":" << port << std::endl;
  12. }
  13. });
  14. string userid = "1";
  15. vector<pair<string, string>> userProfile;
  16. userProfile.push_back(make_pair("name", "John"));
  17. userProfile.push_back(make_pair("age", "35"));
  18. userProfile.push_back(make_pair("language", "Redis"));
  19. // Insert the data
  20. client.hmset(userid, userProfile, [](cpp_redis::reply& reply) {
  21. cout<< "HMSET returned " << reply << ": id=1, name=John, age=35, language=Redis" << endl;
  22. });
  23. // Query the data
  24. client.hgetall(userid, [](cpp_redis::reply& reply) {
  25. std::vector<cpp_redis::reply> retVal;
  26. if (reply.is_array()) {
  27. retVal = reply.as_array();
  28. }
  29. cout << "Query result:" <<endl;
  30. for (int i = 0; i < retVal.size(); i=i+2) {
  31. cout << retVal[i] << "=" <<retVal[i+1] << endl;
  32. }
  33. });
  34. // synchronous commit, no timeout
  35. client.sync_commit();
  36. return 0;
  37. }

Running the application

To compile the file, run the following command.

  1. $ g++ -ltacopie -lcpp_redis -std=c++11 -o ybredis_hello_world ybredis_hello_world.cpp

To run the application, run the following command.

  1. $ ./ybredis_hello_world

You should see the following output.

  1. HMSET returned OK: id=1, name=John, age=35, language=Redis
  2. Query result:
  3. age=35
  4. language=Redis
  5. name=John