下面是一个使用C语言和hiredis库编写的Redis List类型测试例程:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>

int main() {
    redisContext *context = redisConnect("127.0.0.1", 6379); // 连接到Redis服务器
    if (context == NULL || context->err) {
        if (context) {
            printf("Error: %s\n", context->errstr);
        } else {
            printf("Can't allocate redis context\n");
        }
        return 1;
    }

    // 清空List
    redisReply *reply = redisCommand(context, "DEL mylist");
    freeReplyObject(reply);

    // 向List中添加元素
    reply = redisCommand(context, "LPUSH mylist value1");
    freeReplyObject(reply);
    reply = redisCommand(context, "LPUSH mylist value2");
    freeReplyObject(reply);
    reply = redisCommand(context, "LPUSH mylist value3");
    freeReplyObject(reply);

    // 获取List长度
    reply = redisCommand(context, "LLEN mylist");
    printf("List length: %lld\n", reply->integer);
    freeReplyObject(reply);

    // 获取List中的元素
    reply = redisCommand(context, "LRANGE mylist 0 -1");
    if (reply->type == REDIS_REPLY_ARRAY) {
        for (int i = 0; i < reply->elements; i++) {
            printf("Element %d: %s\n", i, reply->element[i]->str);
        }
    }
    freeReplyObject(reply);

    redisFree(context); // 断开连接
    return 0;
}

这个例程首先连接到本地的Redis服务器,然后清空名为'mylist'的List,接着向List中依次插入三个元素,然后获取List的长度并打印,最后获取List中的所有元素并打印。

Redis C语言List类型测试示例 - 使用hiredis库

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

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