|  | 
 
| VC++使用hiredis判断REDIS的key是否存在 在使用  `hiredis`  库判断 Redis 中的 key 是否存在时,可以使用  `EXISTS`  命令。下面是一个简单的示例代码,演示如何使用  `hiredis`  来检查一个 key 是否存在:
 ### 示例代码
 
 复制代码#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
 int main() {
    // 连接到 Redis 服务器
    redisContext *c = redisConnect("127.0.0.1", 6379);
    if (c == NULL || c->err) {
        if (c) {
            printf("连接错误: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("无法分配 Redis 上下文\n");
        }
        return EXIT_FAILURE;
    }
     // 要检查的 key
    const char *key = "mykey";
     // 执行 EXISTS 命令
    redisReply *reply = redisCommand(c, "EXISTS %s", key);
    if (reply == NULL) {
        printf("执行命令错误: %s\n", c->errstr);
        redisFree(c);
        return EXIT_FAILURE;
    }
     // 判断 key 是否存在
    if (reply->integer == 1) {
        printf("Key '%s' 存在\n", key);
    } else {
        printf("Key '%s' 不存在\n", key);
    }
     // 释放回复对象和连接
    freeReplyObject(reply);
    redisFree(c);
     return EXIT_SUCCESS;
}
 ### 代码说明
 1. **连接到 Redis 服务器**:使用  `redisConnect`  函数连接到 Redis 服务器,指定 IP 地址和端口号。
 2. **执行  `EXISTS`  命令**:使用  `redisCommand`  函数执行  `EXISTS`  命令来检查指定的 key 是否存在。
 3. **检查返回结果**:通过  `reply->integer`  检查返回值。如果返回值为  `1` ,表示 key 存在;如果为  `0` ,表示 key 不存在。
 4. **释放资源**:使用  `freeReplyObject`  释放回复对象,使用  `redisFree`  释放 Redis 连接。
 ### 注意事项
 - 确保在运行代码之前已经安装并配置好  `hiredis`  库。
 - 确保 Redis 服务器正在运行,并且可以通过指定的 IP 地址和端口号访问。
 
 
 | 
 |