Redis List 类型 C 语言测试例程 - 使用 hiredis 库
以下是一个使用 C 语言编写的 Redis List 类型测试例程,使用 hiredis 库与 Redis 服务器交互:
#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) {
printf("无法连接到 Redis 服务器: %s\n", context->errstr);
return 1;
}
// 在 List 中插入元素
redisReply *reply = (redisReply *)redisCommand(context, "LPUSH mylist value1");
if (reply == NULL) {
printf("插入元素失败\n");
redisFree(context);
return 1;
}
freeReplyObject(reply);
// 获取 List 的长度
reply = (redisReply *)redisCommand(context, "LLEN mylist");
if (reply == NULL) {
printf("获取 List 长度失败\n");
redisFree(context);
return 1;
}
printf("List 长度为: %lld\n", reply->integer);
freeReplyObject(reply);
// 获取 List 中的元素
reply = (redisReply *)redisCommand(context, "LRANGE mylist 0 -1");
if (reply == NULL) {
printf("获取 List 元素失败\n");
redisFree(context);
return 1;
}
printf("List 中的元素为: ");
for (int i = 0; i < reply->elements; i++) {
printf("%s ", reply->element[i]->str);
}
printf("\n");
freeReplyObject(reply);
redisFree(context); // 关闭与 Redis 服务器的连接
return 0;
}
此例程首先连接到 Redis 服务器,然后使用 LPUSH 命令将一个元素插入到名为 mylist 的 List 中。接下来,使用 LLEN 命令获取 List 的长度,并使用 LRANGE 命令获取 List 中的所有元素。最后,关闭与 Redis 服务器的连接。
请确保已经安装了 hiredis 库,并使用 -lhiredis 参数进行编译。
原文地址: http://www.cveoy.top/t/topic/bQSO 著作权归作者所有。请勿转载和采集!