Redis C 客户端库:List 类型测试例程
下面是一个使用 Redis C 客户端库 hiredis 写的一个 List 类型的测试例程:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis/hiredis.h>
int main() {
// 连接 Redis 服务器
redisContext *ctx = redisConnect('127.0.0.1', 6379);
if (ctx == NULL || ctx->err) {
if (ctx) {
printf("Error: %s\n", ctx->errstr);
redisFree(ctx);
} else {
printf("Cannot connect to Redis server\n");
}
return -1;
}
printf("Connected to Redis server\n");
// 清空已有的 List
redisReply *reply = redisCommand(ctx, "DEL mylist");
freeReplyObject(reply);
// 在 List 的尾部插入元素
reply = redisCommand(ctx, "RPUSH mylist %s", "value1");
freeReplyObject(reply);
// 在 List 的头部插入元素
reply = redisCommand(ctx, "LPUSH mylist %s", "value2");
freeReplyObject(reply);
// 获取 List 中的所有元素
reply = redisCommand(ctx, "LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (int i = 0; i < reply->elements; i++) {
printf("%s\n", reply->element[i]->str);
}
}
freeReplyObject(reply);
// 释放资源,关闭连接
redisFree(ctx);
return 0;
}
这个例程连接到本地的 Redis 服务器(IP 地址为 127.0.0.1,端口号为 6379),然后清空一个名为 mylist 的 List,依次向 List 的尾部和头部插入两个元素,最后获取 List 中的所有元素,并输出到控制台。注意,这个例程使用了 hiredis C 客户端库,你需要先安装该库,然后在编译时链接该库。
原文地址: https://www.cveoy.top/t/topic/bQXY 著作权归作者所有。请勿转载和采集!