Redis C 语言 List 类型操作示例
以下是一个使用 C 语言编写的测试例程,用于对 Redis 中的 List 类型进行操作:
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
redisContext *context = redisConnect("127.0.0.1", 6379);
if (context == NULL || context->err) {
if (context) {
printf("Error: %s\n", context->errstr);
} else {
printf("Can't allocate redis context\n");
}
return 1;
}
redisReply *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: %ld\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;
}
在这个例程中,我们使用了 hiredis 库连接到 Redis 服务器。首先,我们使用 redisConnect 函数连接到本地 Redis 服务器。然后,我们使用 redisCommand 函数执行 Redis 命令,并使用 freeReplyObject 函数释放响应对象。在这个例程中,我们使用了以下几个 Redis 命令:
LPUSH:向 List 中插入元素,插入顺序与命令的执行顺序相反。LLEN:获取 List 的长度。LRANGE:获取 List 中指定范围的元素。
你可以根据自己的需求修改这个例程,并使用其他的 Redis 命令来操作 List 类型。
原文地址: https://www.cveoy.top/t/topic/bQV9 著作权归作者所有。请勿转载和采集!