sewenew / redis-plus-plus

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

Excuse me, So how do you use this object globally? #391

Closed xs-411 closed 2 years ago

xs-411 commented 2 years ago

Here's my example. Is there a better way?

class RedisInstance {
public:
    void init(std::shared_ptr<Redis> redisPtr) {
        redis = std::move(redisPtr);
    }
    static RedisInstance* instance() {
        static RedisInstance redisInstance;
        return &redisInstance;
    }
    std::shared_ptr<Redis> redis;
};

class User {
public:
    void test() {
        std::optional<std::string> key = RedisInstance::instance()->redis->get("key");
    }
};
int main() {
    try {
        ConnectionOptions connection_options;
        connection_options.host = "127.0.0.1";
        connection_options.port = 6379;
        connection_options.socket_timeout = std::chrono::milliseconds(200);
        ConnectionPoolOptions pool_options;
        pool_options.size = 3;
        pool_options.wait_timeout = std::chrono::milliseconds(100);
        std::shared_ptr<Redis> redis(new Redis(connection_options, pool_options));
        RedisInstance::instance()->init(redis);
    } catch (const Error &err) {
    }
    return 0;
}
sewenew commented 2 years ago

Your code should work. However, singleton is an anti-pattern. Avoid using it, if you can.

In your case, why not pass the shared_ptr<Redis> to User? If some other classes also want to use Redis, copy the shared_ptr to it as a data member.

Regards

xs-411 commented 2 years ago

Thank you. I understand。