Skip to content
This repository has been archived by the owner on Apr 6, 2019. It is now read-only.

Examples

Simon Ninon edited this page Aug 15, 2017 · 11 revisions

Redis Client

// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cpp_redis/cpp_redis>

#include <iostream>

#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */

int
main(void) {
#ifdef _WIN32
  //! Windows netword DLL init
  WORD version = MAKEWORD(2, 2);
  WSADATA data;

  if (WSAStartup(version, &data) != 0) {
    std::cerr << "WSAStartup() failure" << std::endl;
    return -1;
  }
#endif /* _WIN32 */

  //! Enable logging
  cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);

  cpp_redis::redis_client client;

  client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&) {
    std::cout << "client disconnected (disconnection handler)" << std::endl;
  });

  // same as client.send({ "SET", "hello", "42" }, ...)
  client.set("hello", "42", [](cpp_redis::reply& reply) {
    std::cout << "set hello 42: " << reply << std::endl;
    // if (reply.is_string())
    //   do_something_with_string(reply.as_string())
  });

  // same as client.send({ "DECRBY", "hello", 12 }, ...)
  client.decrby("hello", 12, [](cpp_redis::reply& reply) {
    std::cout << "decrby hello 12: " << reply << std::endl;
    // if (reply.is_integer())
    //   do_something_with_integer(reply.as_integer())
  });

  // same as client.send({ "GET", "hello" }, ...)
  client.get("hello", [](cpp_redis::reply& reply) {
    std::cout << "get hello: " << reply << std::endl;
    // if (reply.is_string())
    //   do_something_with_string(reply.as_string())
  });

  // commands are pipelined and only sent when client.commit() is called
  // client.commit();

  // synchronous commit, no timeout
  client.sync_commit();

  // synchronous commit, timeout
  // client.sync_commit(std::chrono::milliseconds(100));

#ifdef _WIN32
  WSACleanup();
#endif /* _WIN32 */

  return 0;
}

Redis Subscriber

// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cpp_redis/cpp_redis>

#include <iostream>
#include <signal.h>

#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */

volatile std::atomic<bool> should_exit = ATOMIC_VAR_INIT(false);

void
sigint_handler(int) {
  should_exit = true;
}

int
main(void) {
#ifdef _WIN32
  //! Windows netword DLL init
  WORD version = MAKEWORD(2, 2);
  WSADATA data;

  if (WSAStartup(version, &data) != 0) {
    std::cerr << "WSAStartup() failure" << std::endl;
    return -1;
  }
#endif /* _WIN32 */

  //! Enable logging
  cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);

  cpp_redis::redis_subscriber sub;

  sub.connect("127.0.0.1", 6379, [](cpp_redis::redis_subscriber&) {
    std::cout << "sub disconnected (disconnection handler)" << std::endl;
    should_exit = true;
  });

  //! authentication if server-server requires it
  // sub.auth("some_password", [](const cpp_redis::reply& reply) {
  //   if (reply.is_error()) { std::cerr << "Authentication failed: " << reply.as_string() << std::endl; }
  //   else {
  //     std::cout << "successful authentication" << std::endl;
  //   }
  // });

  sub.subscribe("some_chan", [](const std::string& chan, const std::string& msg) {
    std::cout << "MESSAGE " << chan << ": " << msg << std::endl;
  });
  sub.psubscribe("*", [](const std::string& chan, const std::string& msg) {
    std::cout << "PMESSAGE " << chan << ": " << msg << std::endl;
  });
  sub.commit();

  signal(SIGINT, &sigint_handler);
  while (!should_exit) {}

#ifdef _WIN32
  WSACleanup();
#endif /* _WIN32 */

  return 0;
}

Future Client

// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cpp_redis/cpp_redis>

#include <iostream>

#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */

int
main(void) {
#ifdef _WIN32
  //! Windows netword DLL init
  WORD version = MAKEWORD(2, 2);
  WSADATA data;

  if (WSAStartup(version, &data) != 0) {
    std::cerr << "WSAStartup() failure" << std::endl;
    return -1;
  }
#endif /* _WIN32 */

  //! Enable logging
  cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);

  cpp_redis::future_client client;

  client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&) {
    std::cout << "client disconnected (disconnection handler)" << std::endl;
  });

  //! Set a value
  auto set    = client.set("hello", "42");
  auto decrby = client.decrby("hello", 12);
  auto get    = client.get("hello");

  // commands are pipelined and only sent when client.commit() is called
  client.commit();

  // synchronous commit, no timeout
  // client.sync_commit();

  // synchronous commit, timeout
  // client.sync_commit(std::chrono::milliseconds(100));

  std::cout << "set 'hello' 42: " << set.get() << std::endl;

  cpp_redis::reply r = decrby.get();
  if (r.is_integer())
    std::cout << "After 'hello' decrement by 12: " << r.as_integer() << std::endl;

  std::cout << "get 'hello': " << get.get() << std::endl;

#ifdef _WIN32
  WSACleanup();
#endif /* _WIN32 */

  return 0;
}

Logger

#include <cpp_redis/cpp_redis>

#include <iostream>

class my_logger : public cpp_redis::logger_iface {
public:
  //! ctor & dtor
  my_logger(void) = default;
  ~my_logger(void) = default;

  //! copy ctor & assignment operator
  my_logger(const my_logger&) = default;
  my_logger& operator=(const my_logger&) = default;

public:
  void debug(const std::string& msg, const std::string& file, unsigned int line) {
    std::cout << "debug: " << msg << " @ " << file << ":" << line << std::endl;
  }

  void info(const std::string& msg, const std::string& file, unsigned int line) {
    std::cout << "info: " << msg << " @ " << file << ":" << line << std::endl;
  }

  void warn(const std::string& msg, const std::string& file, unsigned int line) {
    std::cout << "warn: " << msg << " @ " << file << ":" << line << std::endl;
  }

  void error(const std::string& msg, const std::string& file, unsigned int line) {
    std::cerr << "error: " << msg << " @ " << file << ":" << line << std::endl;
  }
};


int
main(void) {
  //! By default, no logging
  //! Force logger call, just for the example (you will never have to do that by yourself)
  std::cout << "By default: no logging" << std::endl;
  _CPP_REDIS_LOG(debug, "This is a debug message");
  _CPP_REDIS_LOG(info, "This is an info message");
  _CPP_REDIS_LOG(warn, "This is a warn message");
  _CPP_REDIS_LOG(error, "This is an error message");
  std::cout << std::endl;

  //! Use the default logger, provided with the library
  cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
  //! Force logger call, just for the example (you will never have to do that by yourself)
  std::cout << "With the library provided logger" << std::endl;
  _CPP_REDIS_LOG(debug, "This is a debug message");
  _CPP_REDIS_LOG(info, "This is an info message");
  _CPP_REDIS_LOG(warn, "This is a warn message");
  _CPP_REDIS_LOG(error, "This is an error message");
  std::cout << std::endl;

  //! Use your custom logger
  cpp_redis::active_logger = std::unique_ptr<my_logger>(new my_logger);
  //! Force logger call, just for the example (you will never have to do that by yourself)
  std::cout << "With an example of custom logger" << std::endl;
  _CPP_REDIS_LOG(debug, "This is a debug message");
  _CPP_REDIS_LOG(info, "This is an info message");
  _CPP_REDIS_LOG(warn, "This is a warn message");
  _CPP_REDIS_LOG(error, "This is an error message");
  std::cout << std::endl;

  return 0;
}

Kill

// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Simon Ninon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include <cpp_redis/cpp_redis>

#include <iostream>
#include <sstream>

#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */

int
main(void) {
#ifdef _WIN32
  //! Windows netword DLL init
  WORD version = MAKEWORD(2, 2);
  WSADATA data;

  if (WSAStartup(version, &data) != 0) {
    std::cerr << "WSAStartup() failure" << std::endl;
    return -1;
  }
#endif /* _WIN32 */

  cpp_redis::redis_client client;

  client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&) {
    std::cout << "client disconnected (disconnection handler)" << std::endl;
  });

  //! client kill ip:port
  client.client_list([&client](cpp_redis::reply& reply) {
    std::string addr;
    std::stringstream ss(reply.as_string());

    ss >> addr >> addr;

    std::string host = std::string(addr.begin() + addr.find('=') + 1, addr.begin() + addr.find(':'));
    int port         = std::stoi(std::string(addr.begin() + addr.find(':') + 1, addr.end()));

    client.client_kill(host, port, [](cpp_redis::reply& reply) {
      std::cout << reply << std::endl; //! OK
    });

    client.commit();
  });

  client.sync_commit();
  std::this_thread::sleep_for(std::chrono::seconds(1));

  if (!client.is_connected()) {
    client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&) {
      std::cout << "client disconnected (disconnection handler)" << std::endl;
    });
  }

  //! client kill filter
  client.client_list([&client](cpp_redis::reply& reply) {
    std::string id_str;
    std::stringstream ss(reply.as_string());

    ss >> id_str;

    uint64_t id = std::stoi(std::string(id_str.begin() + id_str.find('=') + 1, id_str.end()));
    client.client_kill(id, false, cpp_redis::redis_client::client_type::normal, [](cpp_redis::reply& reply) {
      std::cout << reply << std::endl; //! 1
    });

    client.commit();
  });

  client.sync_commit();
  std::this_thread::sleep_for(std::chrono::seconds(1));

#ifdef _WIN32
  WSACleanup();
#endif /* _WIN32 */

  return 0;
}