使用C++通过开启一个子线程并设置定时器来检查 Redis 连接状态以避免掉线

#include <iostream>
#include <redis-cpp/redis.h>
#include <thread>
#include <chrono>

class RedisHandler {
private:
    redis::Connection* connection;
    bool isConnected;
    std::thread monitorThread;

    void checkConnectionAndReconnect();

public:
    RedisHandler();
    ~RedisHandler();
    bool isConnectedToRedis();
};

RedisHandler::RedisHandler() : connection(nullptr), isConnected(false), monitorThread([this]() {
    while (true) {
        checkConnectionAndReconnect();
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
}) {
    try {
        connection = redis::Connection::create("localhost", 6379);
        isConnected = true;
        std::cout << "Connected to Redis." << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Failed to connect to Redis: " << e.what() << std::endl;
    }
}

RedisHandler::~RedisHandler() {
    if (monitorThread.joinable()) {
        monitorThread.join();
    }
    if (connection) {
        delete connection;
    }
}

void RedisHandler::checkConnectionAndReconnect() {
    try {
        if (connection) {
            auto reply = connection->command("PING");
            if (reply && reply->str() == "PONG") {
                // 连接正常,无需修改 isConnected
            } else {
                std::cerr << "Redis connection lost. Trying to reconnect..." << std::endl;
                isConnected = false;
                delete connection;
                connection = redis::Connection::create("localhost", 6379);
                if (connection) {
                    isConnected = true;
                    std::cout << "Reconnected to Redis." << std::endl;
                } else {
                    std::cerr << "Failed to reconnect." << std::endl;
                }
            }
        }
    } catch (const std::exception& e) {
        std::cerr << "Error checking connection: " << e.what() << std::endl;
        isConnected = false;
    }
}

bool RedisHandler::isConnectedToRedis() {
    return isConnected;
}

#include <iostream>
#include <thread>
#include <chrono>
#include <redis-cpp/redis.h>

class Redis {
private:
    redis::Connection* connection;
    bool isConnected;
    std::thread monitorThread;
    void monitorConnection();

public:
    Redis();
    ~Redis();
    void init();
};

Redis::Redis() : isConnected(false), connection(nullptr) {
    try {
        connection = redis::Connection::create("localhost", 6379);
        isConnected = true;
        monitorThread = std::thread(&Redis::monitorConnection, this);
    } catch (const std::exception& e) {
        std::cerr << "Failed to connect to Redis: " << e.what() << std::endl;
    }
}

Redis::~Redis() {
    if (monitorThread.joinable()) {
        monitorThread.join();
    }
    if (connection) {
        delete connection;
    }
}

void Redis::init() {
    if (!isConnected) {
        std::cerr << "Redis not connected. Cannot perform init." << std::endl;
        return;
    }
    // 初始化逻辑...
}

void Redis::monitorConnection() {
    while (true) {
        try {
            if (connection) {
                auto reply = connection->command("PING");
                if (reply && reply->str() == "PONG") {
                    // 连接正常
                } else {
                    std::cerr << "Redis connection lost. Trying to reconnect..." << std::endl;
                    delete connection;
                    connection = redis::Connection::create("localhost", 6379);
                    if (connection) {
                        isConnected = true;
                        std::cout << "Reconnected to Redis." << std::endl;
                    } else {
                        isConnected = false;
                    }
                }
            }
            std::this_thread::sleep_for(std::chrono::seconds(5));
        } catch (const std::exception& e) {
            std::cerr << "Error in connection monitoring: " << e.what() << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(5));
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值