使用QT生成访问RedisI的代码把连接Redis和操作Redis写在不同的方法内相互调用。
下面给出一个简单的示例代码,包括连接Redis和操作Redis的方法:
#include <QDebug>
#include <QTimer>
#include <hiredis/hiredis.h>
class RedisClient : public QObject
{
Q_OBJECT
public:
RedisClient(QObject *parent = nullptr) : QObject(parent)
{
connectToRedis();
}
private:
redisContext *m_redisContext = nullptr;
void connectToRedis()
{
m_redisContext = redisConnect("127.0.0.1", 6379);
if (m_redisContext == nullptr || m_redisContext->err)
{
qWarning() << "Failed to connect to Redis";
return;
}
qInfo() << "Connected to Redis";
}
void operateRedis()
{
if (m_redisContext == nullptr)
{
qWarning() << "Not connected to Redis";
return;
}
redisReply *reply = (redisReply*)redisCommand(m_redisContext, "SET key value");
if (reply == nullptr || reply->type == REDIS_REPLY_ERROR)
{
qWarning() << "Failed to set key value in Redis";
freeReplyObject(reply);
return;
}
qInfo() << "Set key value in Redis";
reply = (redisReply*)redisCommand(m_redisContext, "GET key");
if (reply == nullptr || reply->type == REDIS_REPLY_ERROR)
{
qWarning() << "Failed to get key value from Redis";
freeReplyObject(reply);
return;
}
qInfo() << "Got key value from Redis:" << reply->str;
freeReplyObject(reply);
}
public slots:
void start()
{
QTimer::singleShot(0, this, &RedisClient::operateRedis);
}
};
在此示例代码中,connectToRedis() 方法用于连接 Redis,operateRedis() 方法用于操作 Redis,start() 方法用于启动 Redis 客户端。在 start() 方法中,我们使用 QTimer 来延迟执行 operateRedis() 方法,以确保连接 Redis 后再进行操作。在 operateRedis() 方法中,我们通过 redisCommand() 函数来发送 Redis 命令,并通过 redisReply 结构体来获取命令执行结果。请注意,我们需要在操作完 Redis 后使用 freeReplyObject() 函数释放 redisReply 结构体的内存。
当然,这只是一个简单的示例,实际应用中可能需要更复杂的逻辑和更多的错误处理
原文地址: https://www.cveoy.top/t/topic/ef31 著作权归作者所有。请勿转载和采集!