头文件:

#ifndef REDISCLIENT_H #define REDISCLIENT_H

#include #include "hiredis/hiredis.h"

class RedisClient : public QObject { Q_OBJECT public: explicit RedisClient(QObject *parent = nullptr); ~RedisClient();

bool connectToRedis(const QString& host, int port);
void disconnectFromRedis();

bool set(const QString& key, const QString& value);
QString get(const QString& key);

private: redisContext* m_redisContext; };

#endif // REDISCLIENT_H

源文件:

#include "redisclient.h" #include

RedisClient::RedisClient(QObject *parent) : QObject(parent) { m_redisContext = nullptr; }

RedisClient::~RedisClient() { disconnectFromRedis(); }

bool RedisClient::connectToRedis(const QString &host, int port) { m_redisContext = redisConnect(host.toStdString().c_str(), port); if (m_redisContext == nullptr || m_redisContext->err) { qDebug() << "Failed to connect to Redis server: " << m_redisContext->errstr; return false; } return true; }

void RedisClient::disconnectFromRedis() { if (m_redisContext != nullptr) { redisFree(m_redisContext); m_redisContext = nullptr; } }

bool RedisClient::set(const QString &key, const QString &value) { redisReply* reply = (redisReply*)redisCommand(m_redisContext, "SET %s %s", key.toStdString().c_str(), value.toStdString().c_str()); if (reply == nullptr) { qDebug() << "Failed to execute Redis command: SET"; return false; }

QString strReply = QString::fromUtf8(reply->str, reply->len);
freeReplyObject(reply);

if (strReply == "OK")
{
    return true;
}
else
{
    return false;
}

}

QString RedisClient::get(const QString &key) { redisReply* reply = (redisReply*)redisCommand(m_redisContext, "GET %s", key.toStdString().c_str()); if (reply == nullptr) { qDebug() << "Failed to execute Redis command: GET"; return ""; }

QString strReply = QString::fromUtf8(reply->str, reply->len);
freeReplyObject(reply);

return strReply;
使用QT生成访问RedisI的代码把连接Redis和操作Redis的方法分写在h的头文件和cpp的源文件里面。

原文地址: https://www.cveoy.top/t/topic/ef8h 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录