#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访问Redis:使用Hiredis库实现Redis连接和操作

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

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