cpp_redis is a C++11 Asynchronous Multi-Platform Lightweight Redis Client

Overview

cpp_redis Build Status Build status

cpp_redis is a C++11 Asynchronous Multi-Platform Lightweight Redis Client, with support for synchronous operations, pipelining, sentinels and high availability.

Requirement

cpp_redis has no dependency. Its only requirement is C++11.

It comes with no network module, so you are free to configure your own, or to use the default one (tacopie)

Example

cpp_redis::client

get_reply = client.get("hello"); client.sync_commit(); //! or client.commit(); for asynchronous call ">
cpp_redis::client client;

client.connect();

client.set("hello", "42");
client.get("hello", [](cpp_redis::reply& reply) {
  std::cout << reply << std::endl;
});
//! also support std::future
//! std::future
   
     get_reply = client.get("hello");
   

client.sync_commit();
//! or client.commit(); for asynchronous call

cpp_redis::client full documentation and detailed example. More about cpp_redis::reply.

cpp_redis::subscriber

cpp_redis::subscriber sub;

sub.connect();

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

cpp_redis::subscriber full documentation and detailed example.

Wiki

A Wiki is available and provides full documentation for the library as well as installation explanations.

Doxygen

A Doxygen documentation is available and provides full API documentation for the library.

License

cpp_redis is under MIT License.

Contributing

Please refer to CONTRIBUTING.md.

Special Thanks

Mike Moening for his unexpected and incredible great work aiming to port cpp_redis on Windows, provides sentinel support and high availability support!

Author

Simon Ninon

Issues
  • Retrieving All Keys Available in Redis

    Retrieving All Keys Available in Redis

    Hello, I tried to retrieve all keys available in Redis with this code: client.keys("*", [](cpp_redis::reply& rreply) { std::cout << rreply << std::endl; });

    The output should be like this, so I am able to loop per-line: key1

    key2

    keyn

    But the output is like this: key1key2keyn

    is this a bug? any advice? Thank You. @Cylix @Appkins

    opened by aviezab 6
  • Error with Jan 21, 2017 C++17 bugfix

    Error with Jan 21, 2017 C++17 bugfix

    The bugfix to allow the use of the std::optional function from c++17 doesn't compile when building with c++17. There is a hanging paren after the first #endif in optional.hpp, but in addition, the optional struct defines the bracket operator which is not defined on std::optional. reply.cpp also didn't include the logger.hpp file containing the __CPP_REDIS_LOG macro. Because of the std namespace override, the uses of the optional struct in the code needed to be replaced with optional_t. Additionally, enableIf template needs to be added to the C++17 branch in optional.hpp. Pull request incoming.

    opened by GeoffHadlington 6
  • SSL Support

    SSL Support

    Is your feature request related to a problem? Please describe.

    We can't connect to cloud based Redis servers. For production, they require SSL as the Auth token would otherwise be sent in the clear.

    Describe the solution you'd like

    SSL support. I gather this would be the underlying networking library - if so, has anyone done SSL?

    Describe alternatives you've considered

    There really aren't any :(

    As Tacopie isn't maintained, I checked around. There have been a few forks, but none of them seem to be substantially different. I have a bad feeling hacking in SSL support would be a little bit of work. Maybe that's not cpp_redis's issue, but without it (or support) cpp_redis is useless to us :(

    Great thing to find out just before we're going production .... Doh!

    Additional context

    opened by jgwinner 4
  • Exception thrown in tacopie when publishing

    Exception thrown in tacopie when publishing

    Hi there,

    I really like the platform and thank you for continuing to maintain a great project.

    I have a query though regarding Publishing as it may be broken in the latest build. Although I can subscribe to a channel fine no messages are actually received.. But I noticed that the debug window was showing an exception thrown by tacopie and a memory address. I can't locate the problem however.

    I am running two separate processes - one for pub the other for sub.

    I am using Redis 4.0.

    Any suggestions please?

    Thanks

    opened by lefig 3
  • Update client.cpp

    Update client.cpp

    MY_PATH/cpp_redis-src/sources/core/client.cpp: In member function ‘void cpp_redis::client::sleep_before_next_reconnect_attempt()’:
    MY_PATH/cpp_redis-src/sources/core/client.cpp:347:21: error: ‘sleep_for’ is not a member of ‘std::this_thread’
      347 |   std::this_thread::sleep_for(std::chrono::milliseconds(m_reconnect_interval_msecs));
    
    opened by Manu-sh 2
  • get error when reply.as_string() ,macos 10.15 compile by bazel

    get error when reply.as_string() ,macos 10.15 compile by bazel

    Describe the bug A clear and concise description of what the bug is. i use bazel compile my project. below is my code

    
           cpp_redis::client client;
    
    	client.connect("127.0.0.1", 6379);
    	client.auth("123456");
    
    	std::future<cpp_redis::reply> r2= client.get("hello");
    	client.sync_commit();
    	if(r2.get().is_null()){
    		cout << "null" << endl;
    	}
    	else{
    		cout << "123" << endl;
    		cout << r2.get().as_string()<< endl;
    		cout << "456" << endl;
    	}
    
    

    WORKSPACE

    http_archive(
        name = "redis",
        strip_prefix = "cpp_redis-master",
        url = "https://github.com/cpp-redis/cpp_redis/archive/master.zip",
    )
    
    load("@redis//:repositories.bzl", "cpp_redis_repositories")
    
    cpp_redis_repositories()
    

    BUILD

    cc_binary(
        name = "wasm",
        srcs = ["seclang.cpp"],
        deps = [
        	"@redis//:cpp_redis",
        	":t1"
        	
        ],
        visibility = ["//visibility:public"]
    )
    
    cc_library(
        name = "t1",
        srcs = ["ttt/t1.cpp"],
        hdrs = ["ttt/t1.h"]
    )
    

    build

    bazel build -s //src:wasm
    
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/core/reply.hpp:29:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/optional.hpp:39:
    bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/logger.hpp:135:3: warning: explicitly defaulted copy constructor is implicitly deleted [-Wdefaulted-function-deleted]
      logger(const logger&) = default;
      ^
    bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/logger.hpp:194:14: note: copy constructor of 'logger' is implicitly deleted because field 'm_mutex' has a deleted copy constructor
      std::mutex m_mutex;
                 ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__mutex_base:40:5: note: 'mutex' has been explicitly marked deleted here
        mutex(const mutex&) = delete;
        ^
    In file included from src/seclang.cpp:11:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/cpp_redis:30:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/core/client.hpp:36:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/core/types.hpp:31:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/core/reply.hpp:29:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/optional.hpp:39:
    bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/logger.hpp:140:11: warning: explicitly defaulted copy assignment operator is implicitly deleted [-Wdefaulted-function-deleted]
      logger& operator=(const logger&) = default;
              ^
    bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/misc/logger.hpp:194:14: note: copy assignment operator of 'logger' is implicitly deleted because field 'm_mutex' has a deleted copy assignment operator
      std::mutex m_mutex;
                 ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__mutex_base:41:12: note: 'operator=' has been explicitly marked deleted here
        mutex& operator=(const mutex&) = delete;
               ^
    In file included from src/seclang.cpp:11:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/cpp_redis:41:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/network/tcp_client.hpp:28:
    In file included from bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/tacopie:30:
    In file included from bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/error.hpp:29:
    bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/logger.hpp:107:3: warning: explicitly defaulted copy constructor is implicitly deleted [-Wdefaulted-function-deleted]
      logger(const logger&) = default;
      ^
    bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/logger.hpp:157:14: note: copy constructor of 'logger' is implicitly deleted because field 'm_mutex' has a deleted copy constructor
      std::mutex m_mutex;
                 ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__mutex_base:40:5: note: 'mutex' has been explicitly marked deleted here
        mutex(const mutex&) = delete;
        ^
    In file included from src/seclang.cpp:11:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/cpp_redis:41:
    In file included from bazel-out/darwin-fastbuild/bin/external/redis/_virtual_includes/cpp_redis/cpp_redis/network/tcp_client.hpp:28:
    In file included from bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/tacopie:30:
    In file included from bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/error.hpp:29:
    bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/logger.hpp:109:11: warning: explicitly defaulted copy assignment operator is implicitly deleted [-Wdefaulted-function-deleted]
      logger& operator=(const logger&) = default;
              ^
    bazel-out/darwin-fastbuild/bin/external/tacopie/_virtual_includes/tacopie/tacopie/utils/logger.hpp:157:14: note: copy assignment operator of 'logger' is implicitly deleted because field 'm_mutex' has a deleted copy assignment operator
      std::mutex m_mutex;
                 ^
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/__mutex_base:41:12: note: 'operator=' has been explicitly marked deleted here
        mutex& operator=(const mutex&) = delete;
               ^
    4 warnings generated.
    Target //src:wasm up-to-date:
      bazel-bin/src/wasm
    INFO: Elapsed time: 0.881s, Critical Path: 0.81s
    INFO: 2 processes: 1 internal, 1 darwin-sandbox.
    INFO: Build completed successfully, 2 total actions
    

    run

    
    [email protected] ctgw_wasm % bazel run -s //src:wasm
    DEBUG: Rule 'redis' indicated that a canonical reproducible form can be obtained by modifying arguments sha256 = "666243fefb1465c0f9e6cd7fba0eab099e8aa7469674fecfc246f572705543ab"
    DEBUG: Repository redis instantiated at:
      no stack (--record_rule_instantiation_callstack not enabled)
    Repository rule http_archive defined at:
      /private/var/tmp/_bazel_dengxiaoqian/52cacb9c84a09b383e18d0ecdbf561f4/external/bazel_tools/tools/build_defs/repo/http.bzl:336:31: in <toplevel>
    INFO: Analyzed target //src:wasm (0 packages loaded, 0 targets configured).
    INFO: Found 1 target...
    Target //src:wasm up-to-date:
      bazel-bin/src/wasm
    INFO: Elapsed time: 0.077s, Critical Path: 0.00s
    INFO: 1 process: 1 internal.
    INFO: Build completed successfully, 1 total action
    INFO: Build completed successfully, 1 total action
    !!!Hello World111!!!
    123
    
    

    console not print the value of 'hello' and '456'

    what cause the problem?

    opened by dxq174510447 2
  • error while compile

    error while compile

    Describe the bug I try to test code in the example markdown as :

    #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::client client;
    
      client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
        if (status == cpp_redis::client::connect_state::dropped) {
          std::cout << "client disconnected from " << host << ":" << port << 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;
    }
    

    I follow the command line in https://github.com/cpp-redis/cpp_redis/wiki/Mac-&-Linux-Install to install cpp_redis

    and use

    gcc -lstdc++ -lcpp_redis -ltacopie --std=c++11 test_redis.cpp -o testredis
    

    to compile the code.

    But it come out a error :

    bash-5.0# gcc -lstdc++ -lcpp_redis -ltacopie --std=c++11 test_redis.cpp -o testredis
    test_redis.cpp: In function 'int main()':
    test_redis.cpp:27:104: error: 'cpp_redis::client::connect_state' has not been declared
       27 |     client.connect("127.0.0.1", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
          |                                                                                                        ^~~~~~~~~~~~~
    test_redis.cpp: In lambda function:
    test_redis.cpp:28:46: error: 'cpp_redis::client::connect_state' has not been declared
       28 |             if (status == cpp_redis::client::connect_state::dropped) {
          |                                              ^~~~~~~~~~~~~
    test_redis.cpp: In function 'int main()':
    test_redis.cpp:31:14: error: no matching function for call to 'cpp_redis::client::connect(const char [10], int, main()::<lambda(const string&, std::size_t, int)>)'
       31 |             });
          |              ^
    In file included from /usr/local/include/cpp_redis/cpp_redis:30,
                     from test_redis.cpp:1:
    /usr/local/include/cpp_redis/core/client.hpp:116:9: note: candidate: 'void cpp_redis::client::connect(const string&, std::size_t, const connect_callback_t&, uint32_t, int32_t, uint32_t)'
      116 |    void connect(
          |         ^~~~~~~
    /usr/local/include/cpp_redis/core/client.hpp:119:32: note:   no known conversion for argument 3 from 'main()::<lambda(const string&, std::size_t, int)>' to 'const connect_callback_t&' {aka 'const std::function<void(const std::__cxx11::basic_string<char>&, long unsigned int, cpp_redis::connect_state)>&'}
      119 |      const connect_callback_t &connect_callback = nullptr,
          |      ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
    /usr/local/include/cpp_redis/core/client.hpp:134:9: note: candidate: 'void cpp_redis::client::connect(const string&, const connect_callback_t&, uint32_t, int32_t, uint32_t)'
      134 |    void connect(
          |         ^~~~~~~
    /usr/local/include/cpp_redis/core/client.hpp:136:32: note:   no known conversion for argument 2 from 'int' to 'const connect_callback_t&' {aka 'const std::function<void(const std::__cxx11::basic_string<char>&, long unsigned int, cpp_redis::connect_state)>&'}
      136 |      const connect_callback_t &connect_callback = nullptr,
          |      ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~
    

    To Reproduce Steps to reproduce the behavior:

    1. follow https://github.com/cpp-redis/cpp_redis/wiki/Mac-&-Linux-Install to install cpp_redis
    2. copy code in https://github.com/cpp-redis/cpp_redis/wiki/Examples#redis-client to a file(test_redis.cpp)
    3. try gcc -lstdc++ -lcpp_redis -ltacopie --std=c++11 test_redis.cpp -o testredis to compile

    Expected behavior compile success with no error or warning.

    Screenshots all codes, steps and outputs have been shown above.

    Desktop (please complete the following information):

    • firecracker microVM
    • uname -a : Linux dab7670245ef 4.15.0-91-generic #92-Ubuntu SMP Fri Feb 28 11:09:48 UTC 2020 x86_64 Linux
    • alpine
    opened by zhuangh7 2
  • Cannot Use cpp_redis with CMake and VCPKG

    Cannot Use cpp_redis with CMake and VCPKG

    Describe the bug Trying to create a Docker image for a C++ application using cpp-redis installed with VCPKG and built with CMake 13.4.5:

    [100%] Linking CXX executable micro-service /usr/bin/ld: cannot find -lcpp_redis /usr/bin/ld: cannot find -ltacopie collect2: error: ld returned 1 exit status make[2]: *** [micro-service] Error 1

    This doesn't happen on my Ubuntu 1804.

    A temporary solution would be providing full path for the files like this:

            ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/libcpp_redis.a
            ${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/libtacopie.a
    

    For some reason I need that only in the case of cpp-redis and tacopie.

    I tried using pkg-config which could find the library but I still had the same errors only in Docker:

    find_package(PkgConfig REQUIRED)
    pkg_check_modules(cpp_redis REQUIRED cpp_redis)
    
    

    Making verbose build generates the same building command both in my Ubuntu and inside Docker. However, I get the error only in Docker: /usr/bin/c++ -O3 -DNDEBUG CMakeFiles/micro-service.dir/main.cpp.o CMakeFiles/micro-service.dir/microsvc_controller.cpp.o CMakeFiles/micro-service.dir/foundation/basic_controller.cpp.o CMakeFiles/micro-service.dir/cache/redis_cache.cpp.o -o micro-service /usr/lib64/libsoci_sqlite3.so.4.0.0 /tmp/vcpkg/installed/x64-linux/lib/libfmt.a -lcpp_redis -ltacopie /tmp/vcpkg/installed/x64-linux/lib/libhttp_parser.a /usr/lib64/libsoci_core.so.4.0.0 -lpthread /usr/lib/x86_64-linux-gnu/libdl.so /tmp/vcpkg/installed/x64-linux/lib/libsqlite3.a

    To Reproduce Steps to reproduce the behavior:

    1. Download this project https://github.com/ahmedyarub/micro-service
    2. Do docker build .

    Expected behavior A Docker image is created without errors

    Desktop (please complete the following information):

    • OS: Ubuntu 18.04
    • Version: 4.3.1-1
    opened by ahmedyarub 2
  • fail Socket()

    fail Socket()

    Hi there, i've created a minimal c++17 project, to test the library on windows, but when i run the code from below i get the error fail Socket().

    #include <iostream>
    #include "cpp_redis/cpp_redis"
    
    int main(int argc, char* argv[])
    {
    	try {
    		cpp_redis::client client;
    		client.connect();
    	} catch(std::exception& e)
    	{
    		std::cout << e.what() << std::endl;
    	}
    
    	std::cin.get();
    	return 0;
    }
    

    Project was generated using the following premake5 file:

    project "test"
    	language "C++"
    	cppdialect "C++17"
    	kind "ConsoleApp"
    
    	libdirs { "lib" }
    
    	vpaths {
    		["Headers/*"] = "**.h",
    		["Sources/*"] = "**.cpp",
    		["Test files"] = "**.json",
    		["*"] = "premake5.lua"
    	}
    
    	files {
    		"premake5.lua",
    		"**.cpp",
    		"**.h",
    	}
    
    	filter { "system:windows", "platforms:x86" }
    		links { "tacopie.lib" }
    		links { "cpp_redis.lib" }
    	
    	filter { "system:windows", "platforms:x64" }
    		links { "tacopie_64.lib" }
    		links { "cpp_redis_64.lib" }
    
    	filter "system:linux"
    
    opened by StiviiK 2
  • undefined reference to `operator<<(std::ostream&, cpp_redis::reply const&)'

    undefined reference to `operator<<(std::ostream&, cpp_redis::reply const&)'

    I followed the installation procedure (https://github.com/Cylix/cpp_redis/wiki/Mac-&-Linux-Install), using the updated library instead of the old one:

    # ... rest of procedure described in link
    git clone https://github.com/cpp-redis/cpp_redis.git
    # ... rest of procedure described in link
    

    Now when I try to run a program (even

    cpp_redis_client.cpp

    in the example dir) I got the error:

    /tmp/ccptfGnr.o: In function `main::{lambda(cpp_redis::reply&)#1}::operator()(cpp_redis::reply&) const':
    ex0.cpp:(.text+0xc5): undefined reference to `operator<<(std::ostream&, cpp_redis::reply const&)'
    /tmp/ccptfGnr.o: In function `main':
    ex0.cpp:(.text+0x105): undefined reference to `cpp_redis::client::client()'
    ex0.cpp:(.text+0x17c): undefined reference to `cpp_redis::client::connect(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, std::function<void (std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned long, cpp_redis::connect_state)> const&, unsigned int, int, unsigned int)'
    ex0.cpp:(.text+0x223): undefined reference to `cpp_redis::client::set(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
    ex0.cpp:(.text+0x2bd): undefined reference to `cpp_redis::client::get(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::function<void (cpp_redis::reply&)> const&)'
    ex0.cpp:(.text+0x2f0): undefined reference to `cpp_redis::client::sync_commit()'
    ex0.cpp:(.text+0x304): undefined reference to `cpp_redis::client::~client()'
    ex0.cpp:(.text+0x3ca): undefined reference to `cpp_redis::client::~client()'
    collect2: error: ld returned 1 exit status
    

    I tried with#include <iostream>but nothing worked.

    Here my code:

    #include <string>
    #include <cpp_redis/cpp_redis>
    #include <cpp_redis/misc/macro.hpp>
    #include <iostream>
    
    /*
    to compile:
    gcc -lstdc++ --std=c++11  \
        ex0.cpp \
        -o ex0 \
        && time ./ex0
    */
    
    int main(int argc, char const *argv[]) {
    
    //    cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
    
        cpp_redis::client client;
    
        client.connect();
    
        client.set("hello", "42");
        client.get("hello", [](cpp_redis::reply& reply) {
          std::cout << reply << std::endl;
        });
        //! also support std::future
        //! std::future<cpp_redis::reply> get_reply = client.get("hello");
    
        client.sync_commit();
        //! or client.commit(); for asynchronous call
    
        return 0;
    }
    

    Compiled through gcc: gcc -lstdc++ --std=c++11 ex0.cpp -o ex0 Thanks a lot in advance for any help!

    question 
    opened by cccnrc 2
  • "cpp_redis::client" has no member "connect_state"

    When I try to build a VS console app with cpp_redis, the build fails with the error "cpp_redis::client" has no member "connect_state". I actually started with cpp_redis in an Unreal Engine 4 application where I first saw the issue. I figured it could be related to something in UE4 so tested it out in a console application where I get the same error.

    VS 2017 v1.41 Build tools with 10.xx SDK x64 and Release configuration

    Both cpp_redis and tacopie build successfully with no warnings.

    The following snippet from the console application builds successfully so I'm pretty sure that I'm linking the two libs properly.

    cpp_redis::client client;
    client.connect();
    

    When I try to connect with the following I get the build error referenced above.

    client.connect("192.168.0.179", 6379, [](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
    	if (status == cpp_redis::client::connect_state::dropped) {
    		std::cout << "client disconnected from " << host << ":" << port << std::endl;
    	}
    }); 
    

    I get the same error when I try to connect a subscriber. I can't find any reference to anybody else having this problem so it's got to be something specific to me, especially since I see it in two different applications, but I just don't know what. Any ideas what I'm doing wrong?

    opened by oluf 2
  • Using sentinel, some commands 'send' hangs

    Using sentinel, some commands 'send' hangs

    Describe the bug When using Redis sentinel - 1 master, 2 duplicates, 3 sentinels - I can always connect to the (curent) writeable master.

    However, if I 'stop' that service, the next command hangs.

    This may not be a bug, maybe it's proper use of Sentinel, but if this is the case the examples and/or docs should probably be updated. I can do a PR if that's the case.

    To Reproduce Steps to reproduce the behavior:

    1. Implement Redis Sentinel
    2. Connect to the current master
    3. Issue an 'lpop' command:
    	redisClient->lpop(GetQueue().toStdString(), [&webReply,&bError](cpp_redis::reply& charRequest) {
                          .... stuff ... 
    		});
    	redisClient->sync_commit(std::chrono::milliseconds(5000)); 
    
    1. It works fine.
    2. stop the current master. The slaves will fail over and promote a new master.
    3. The next 'lpop' command hangs down inside this routine:
    client::send(const std::vector<std::string> &redis_cmd, const reply_callback_t &callback) {
    	std::lock_guard<std::mutex> lock_callback(m_callbacks_mutex);
    	__CPP_REDIS_LOG(info, "cpp_redis::client attempts to store new command in the send buffer");
    	unprotected_send(redis_cmd, callback);
    	__CPP_REDIS_LOG(info, "cpp_redis::client stored new command in the send buffer");
    
    

    Expected behavior I would think issuing any serial commands to a connection that can't take it should result in a tacopie or cpp_redis error being thrown.

    Possible workaround My routine that does the connect DOES immediately exits out:

    	LOG_INFO << "Connecting to HA Redis servers with " << iSentinels << "sentinels";
    	bool bDisconnect = false;
    	redisClient->connect("ourcluster", [&bDisconnect](const std::string& host, std::size_t port, cpp_redis::connect_state status) {
    		if (status == cpp_redis::connect_state::dropped) {
    			LOG_INFO << "Client disconnected from " << host.c_str() << ":" << port;
    

    The 'dropped' fires right off, so I could assign a bool value, and then in the outer loop, before every command check to see if we're disconnected - but that seems like a lot of potential boilerplate code.

    I guess I could also just try to reconnect inside the 'connect' callback? Is that the right way to do it? The code example didn't show this

    Desktop (please complete the following information):

    • OS: [Windows 10]
    • Browser [n/a]
    • Version [Current]
    opened by jgwinner 0
  • Can you provide an interface that calls back on the main thread?

    Can you provide an interface that calls back on the main thread?

    Hello, I am a game server developer. When we use cpp_redis, there will be a need to call back on the main thread.

    At present, I have sealed it with asio to temporarily meet the needs. Would like to ask if the official can provide such an interface. Or there are others with similar needs. My own example: https://github.com/brinkqiang/dmredispp

    #include <cpp_redis/cpp_redis>
    
    #include <iostream>
    
    #ifdef _WIN32
    #include <Winsock2.h>
    #endif /* _WIN32 */
    #include "dmevent/dmevent_module.h"
    
    
    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 */
    
        DMEVENT_INIT();
        DMEVENT_BEGIN
        {
            fmt::print("-------------------------------------------- -------------------\n");
            fmt::print("{} dmevent loop {} ...\n", DMGetExeName(), "running");
            fmt::print("-------------------------------------------- -------------------\n");
        }
        DMEVENT_END;
    
    
        //! Enable logging
        cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
    
        cpp_redis::client client;
    
        client.connect("127.0.0.1", 6379, [&](const std::string& host, std::size_t port, cpp_redis::client::connect_state status) {
            DMEVENT_BEGIN
            {
                if (status == cpp_redis::client::connect_state::dropped) {
                    fmt::print("client disconnected from {}:{} isMain:{}\n", host, port, isMain());
                }
            }
            DMEVENT_END;
        });
    
        int roleid = 0x1234;
        // same as client. send({ "SET", "hello", "42" }, ...)
        client.set("hello", "42", [&](cpp_redis::reply& reply) {
            DMEVENT_BEGIN
            {
                fmt::print("set hello 42: {} roleid: {} isMain:{}\n", reply, roleid, isMain());
            }
            DMEVENT_END;
        });
    
        // same as client. send({ "DECRBY", "hello", 12 }, ...)
        client.decrby("hello", 12, [&](cpp_redis::reply& reply) {
            DMEVENT_BEGIN
            {
                fmt::print("decrby hello 12: {} roleid: {} isMain:{}\n", reply, roleid, isMain());
            }
            DMEVENT_END;
        });
    
        // same as client. send({ "GET", "hello" }, ...)
        client.get("hello", [&](cpp_redis::reply& reply) {
            DMEVENT_BEGIN
            {
                fmt::print("get hello: {} roleid: {} isMain:{}\n", reply, roleid, isMain());
            }
            DMEVENT_END;
        });
    
        // commands are pipelined and only sent when client.commit() is called
        client.commit();
    
        DMEVENT_RUN_UNTIL();
        // synchronous commit, no timeout
        //client.sync_commit();
    
        // synchronous commit, timeout
        // client.sync_commit(std::chrono::milliseconds(100));
    
    #ifdef _WIN32
        WSACleanup();
    #endif /* _WIN32 */
    
        return 0;
    }
    
    opened by brinkqiang 0
  • Create a client pool

    Create a client pool

    #83 Just opened this PR to introduce a client pool. This will allow user code to easily access the functionality from multiple threads, without extra facilities for synchronization.

    My question would be:

    • Is this a desired idea?
    • The provided example gives me unexpected results. I thoroughly checked that there are no data races in my code. Is it possible to have multiple threads use different client instances to issue commands?
    opened by picanumber 0
  • Introduce client pool

    Introduce client pool

    The client pool is used to create the desired number of client instances which are accessible in a thread safe fashion.

    Different threads can assign a task to the pool, by calling the ::run method; this is a method that accepts a callback with a signature <Ret(client *)> where Ret is any type. Inside that callback, the provided client is accessed in a thread safe manner.

    Selection of an idle client from the pool is done in a round robin fashion and will wait to find an idle "worker" when all clients in the pool are busy.

    Also added an example.

    opened by picanumber 0
Releases(4.4.0-beta.1)
  • 4.4.0-beta.1(Mar 24, 2019)

    In addition to introducing support for Redis Streams, this release adds a consumer client that processes background work. The threading requires no additional libraries and is highly efficient.

    https://redis.io/topics/streams-intro

    Source code(tar.gz)
    Source code(zip)
Owner
CPP Redis
CPP Redis
A redis module, similar to redis zset, but you can set multiple scores for each member to support multi-dimensional sorting

TairZset: Support multi-score sorting zset Introduction Chinese TairZset is a data structure developed based on the redis module. Compared with the na

Alibaba 43 Jun 15, 2022
Modern, asynchronous, and wicked fast C++11 client for Redis

redox Modern, asynchronous, and wicked fast C++11 client for Redis [] (https://travis-ci.org/hmartiro/redox) Redox is a C++ interface to the Redis key

Hayk Martiros 374 Jun 14, 2022
redis-cpp is a header-only library in C++17 for Redis (and C++11 backport)

redis-cpp - lightweight C++ client library for Redis redis-cpp is a C++17 library for executing Redis commands with support for pipelines and the publ

null 69 Jun 30, 2022
Minimalistic C client for Redis >= 1.2

This Readme reflects the latest changed in the master branch. See v1.0.0 for the Readme and documentation for the latest release (API/ABI history). HI

Redis 5.3k Jun 29, 2022
Redis client written in C++

redis-plus-plus Overview Features Branches Installation Install hiredis Install redis-plus-plus Run Tests (Optional) Use redis-plus-plus In Your Proje

null 871 Jul 4, 2022
Aredis - a clean redis C++ client

aredis a clean redis C++ client redis_conn rc; if (rc.connect("127.0.0.1"/*host*/, 6379/*port*/, nullptr/*password*/, 1/*db*/)) { redis_command cmd;

Evan 26 Dec 10, 2021
A C++ Redis client

redis3m A C++ Redis client, born to bring my experience using Redis and C++ on a opensource library. Main goals Provide a simple and efficient wrapper

Luca Marturana 184 Apr 21, 2022
StarRocks is a next-gen sub-second MPP database for full analysis senarios, including multi-dimensional analytics, real-time analytics and ad-hoc query, formerly known as DorisDB.

StarRocks is a next-gen sub-second MPP database for full analysis senarios, including multi-dimensional analytics, real-time analytics and ad-hoc query, formerly known as DorisDB.

StarRocks 2.7k Jun 26, 2022
A lightweight header-only C++11 library for quick and easy SQL querying with QtSql classes.

EasyQtSql EasyQtSql is a lightweight header-only C++11 library for quick and easy SQL querying with QtSql classes. Features: Header only C++11 library

null 44 Jun 28, 2022
A friendly and lightweight C++ database library for MySQL, PostgreSQL, SQLite and ODBC.

QTL QTL is a C ++ library for accessing SQL databases and currently supports MySQL, SQLite, PostgreSQL and ODBC. QTL is a lightweight library that con

null 155 Jun 26, 2022
A very fast lightweight embedded database engine with a built-in query language.

upscaledb 2.2.1 Fr 10. Mär 21:33:03 CET 2017 (C) Christoph Rupp, [email protected]; http://www.upscaledb.com This is t

Christoph Rupp 531 Jun 20, 2022
Lightweight C++ wrapper for SQLite

NLDatabase Lightweight C++ wrapper for SQLite. Requirements C++11 compiler SQLite 3 Usage Let's open a database file and read some rows: #include "NLD

Raven 0 Sep 20, 2019
The official C++ client API for PostgreSQL.

libpqxx Welcome to libpqxx, the C++ API to the PostgreSQL database management system. Home page: http://pqxx.org/development/libpqxx/ Find libpqxx on

Jeroen Vermeulen 643 Jun 25, 2022
Beryl-cli is a client for the BerylDB database server

Beryl-cli is a client for the BerylDB database server. It offers multiple commands and is designed to be fast and user-friendly.

BerylDB 11 Apr 21, 2022
The PostgreSQL client API in modern C++

C++ client API to PostgreSQL {#mainpage} Dmitigr Pgfe (PostGres FrontEnd, hereinafter referred to as Pgfe) - is a C++ client API to PostgreSQL servers

Dmitry Igrishin 134 Jun 3, 2022
C++ client library for PostgreSQL

Welcome to taoPQ taoPQ is a lightweight C++ client library for accessing a PostgreSQL➚ database. It has no dependencies beyond libpq➚, the C applicati

The Art of C++ 213 Jun 22, 2022
Trilogy is a client library for MySQL-compatible database servers, designed for performance, flexibility, and ease of embedding.

Trilogy is a client library for MySQL-compatible database servers, designed for performance, flexibility, and ease of embedding.

GitHub 248 Jun 11, 2022
Serverless SQLite database read from and write to Object Storage Service, run on FaaS platform.

serverless-sqlite Serverless SQLite database read from and write to Object Storage Service, run on FaaS platform. NOTES: This repository is still in t

老雷 7 May 12, 2022
An open-source big data platform designed and optimized for the Internet of Things (IoT).

An open-source big data platform designed and optimized for the Internet of Things (IoT).

null 18.6k Jul 1, 2022