在 Linux 中链接 Redis
Redis 是一种流行的内存数据结构存储,可用于缓存、消息传递和其他用例。在本文中,我们将介绍如何在 Linux 中链接 Redis。
在 Linux 中链接 Redis
在 Linux 中链接 Redis
先决条件
安装 Linux 作系统 安装 Redis 拥有 sudo 权限
步骤
1. 安装 Redis 开发包
首先,安装 Redis 开发包,其中包含用于链接 Redis 的库。
``` sudo apt-get install redis-dev ```
2. 创建 C 程序
创建一个名为 `redis_example.c` 的新 C 程序文件。
3. 包含必需的标题
在程序中包含必需的 Redis 标题。
```c
include
4. 创建 Redis 链接
创建与 Redis 的链接。
```c redisContext ctx = redisConnect("127.0.0.1", 6379); if (ctx == NULL) { fprintf(stderr, "无法连接到 Redis n"); exit(1); } ```
5. 使用 Redis
使用 `redisCommand()` 函数向 Redis 发送命令。
```c redisReply reply = redisCommand(ctx, "GET my_key"); if (reply == NULL) { fprintf(stderr, "无法获取 keyn"); exit(1); } ```
6. 处理响应
检查响应并根据需要处理数据。
```c if (reply->type == REDIS_REPLY_STRING) { printf("key 的值:%sn", reply->str); } ```
7. 关闭链接
最终,关闭与 Redis 的链接。
```c redisFree(reply); redisFree(ctx); ```
示例代码
```c
include
int main() { redisContext ctx = redisConnect("127.0.0.1", 6379); if (ctx == NULL) { fprintf(stderr, "无法连接到 Redis n"); exit(1); }
redisReply reply = redisCommand(ctx, "SET my_key my_value"); if (reply == NULL) { fprintf(stderr, "无法设置 keyn"); exit(1); }
reply = redisCommand(ctx, "GET my_key"); if (reply == NULL) { fprintf(stderr, "无法获取 keyn"); exit(1); }
if (reply->type == REDIS_REPLY_STRING) { printf("key 的值:%sn", reply->str); }
redisFree(reply); redisFree(ctx); return 0; } ```
编译和运行
编译程序:
``` gcc -o redis_example redis_example.c -lhiredis ```
运行程序:
``` ./redis_example ```