以下是使用QT和hiredis包访问Redis的示例代码:

#include <QtCore/QCoreApplication>
#include <hiredis/hiredis.h>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 连接到Redis服务器
    redisContext *redis = redisConnect('127.0.0.1', 6379);

    if (redis == NULL || redis->err) {
        if (redis) {
            printf("Error: %s\n", redis->errstr);
            redisFree(redis);
        } else {
            printf("Can't allocate redis context\n");
        }
        return 1;
    }

    // 将值推入列表
    redisReply *reply = (redisReply*)redisCommand(redis, "LPUSH mylist 1");

    if (reply == NULL) {
        printf("Error: Failed to push value onto list\n");
        redisFree(redis);
        return 1;
    }

    freeReplyObject(reply);

    // 从列表中弹出值
    reply = (redisReply*)redisCommand(redis, "RPOP mylist");

    if (reply == NULL) {
        printf("Error: Failed to pop value off list\n");
        redisFree(redis);
        return 1;
    }

    printf("Popped value: %s\n", reply->str);

    freeReplyObject(reply);

    redisFree(redis);

    return a.exec();
}

在这个示例中,我们使用hiredis库连接到本地Redis服务器,并使用LPUSH和RPOP命令将值推送到列表中并从列表中弹出值。请注意,我们使用redisCommand函数执行Redis命令,并使用redisReply结构处理返回的结果。

使用QT和hiredis操作Redis: 示例代码和操作方法

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

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