sewenew / redis-plus-plus

Redis client written in C++
Apache License 2.0
1.64k stars 351 forks source link

If redis is not started, the asynchronous interface will be blocked forever #336

Closed nqf closed 2 years ago

nqf commented 2 years ago
#include <sw/redis++/async_redis++.h>

#include <iostream>

int main() {
    sw::redis::ConnectionOptions opts;
    opts.host = "127.0.0.1";
    opts.port = 6379;
    sw::redis::ConnectionPoolOptions pool_opts;
    pool_opts.size = 3;
    std::shared_ptr<sw::redis::AsyncRedis> async_redis_ptr = std::make_shared<sw::redis::AsyncRedis>(opts, pool_opts);
    async_redis_ptr->get("key").then([](sw::redis::Future<sw::redis::Optional<std::string>> fut) mutable {
        std::cout << "start get" << std::endl;
        auto opt = fut.get();
        std::cout << "get end" << std::endl;
        if (!opt) {
            std::cout << "dddddddddd:" << std::endl;
            return;
        }
    });
    std::cout << "start block...." << std::endl;
    while (1)
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    return 0;
}

[root@80306e506575 build]# ./test_spawn 
start block....
start get

[root@80306e506575 tmp]# redis-server
1246:C 11 Mar 2022 03:09:59.944 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
1246:C 11 Mar 2022 03:09:59.944 # Redis version=255.255.255, bits=64, commit=1797330e, modified=0, pid=1246, just started
nqf commented 2 years ago

When I start the redis service , future will not return image

sewenew commented 2 years ago

Redis is killed, and redis-plus-plus cannot connect to it. So when you try to get the result, i.e. auto opt = fut.get(), it throws exception. That's how std::future, and boost::future works, i.e. use exception to indicate error.

You can modify your code as follows to see how it works:

try {
    auto opt = fut.get();
    // other code
} catch (...) {
   cout << "got exception" << endl;
}

Regards

nqf commented 2 years ago

Thanks