用c++语言操作Redis,当使用get命令时,由于不存在的key时程序崩溃解决办法

前言

今天在写项目的时候调用Redis的时候,程序一直崩溃,最后发现昨天在Redis设置的键值对过期了,导致Redis中没有需要的键值对。所以在程序中调用get命令就出错了,所以在调用redisCommand函数之后需要再进一步判断其返回值。

redisContext* handle;
std::string Redis::rd_get(std::string key)
{
 
        redisReply *reply = (redisReply *)redisCommand(this->handle, "GET %s", key.c_str());
        std::string value(reply->str);
        // 释放redisCommand执行后返回的的redisReply所占用的内存
        freeReplyObject(reply);
        return value;
}

代码没有截全,handle是在Redis类里面定义的,是redisConnect函数的返回结果

我在reply结果的前面和后面都用过cout语句,但是只要打印出reply->str就会出现段错误,我就去Redis数据库查看,发现昨天的键值对已经过期了,我于是加入键值对之后又测试,程序正常。之后发现只要get数据库中不存在的键值对程序就崩溃,所以必须得给get这个操作后采取措施。

对redisReply不是很熟悉,就点进hiredis.h库去看它的实现

typedef struct redisReply {
    int type; /* REDIS_REPLY_* */
    long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
    double dval; /* The double when type is REDIS_REPLY_DOUBLE */
    size_t len; /* Length of string */
    char *str; /* Used for REDIS_REPLY_ERROR, REDIS_REPLY_STRING
                  REDIS_REPLY_VERB, and REDIS_REPLY_DOUBLE (in additional to dval). */
    char vtype[4]; /* Used for REDIS_REPLY_VERB, contains the null
                      terminated 3 character content type, such as "txt". */
    size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
    struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;

之后又进到read.h看到了type的各种定义,但是我实验过用type=REDIS_REPLY_ERROR等去判断都失败了

#define REDIS_REPLY_STRING 1
#define REDIS_REPLY_ARRAY 2
#define REDIS_REPLY_INTEGER 3
#define REDIS_REPLY_NIL 4
#define REDIS_REPLY_STATUS 5
#define REDIS_REPLY_ERROR 6
#define REDIS_REPLY_DOUBLE 7
#define REDIS_REPLY_BOOL 8
#define REDIS_REPLY_MAP 9
#define REDIS_REPLY_SET 10
#define REDIS_REPLY_ATTR 11
#define REDIS_REPLY_PUSH 12
#define REDIS_REPLY_BIGNUM 13
#define REDIS_REPLY_VERB 14

网上说Redis 的get不存在键的返回值是nil,我用reply->str == “nil”和NULL测试过都不行

最后我用reply->len == 0判断成功了,成功阻止了程序崩溃。网上关于这一部分讲解基本没有,最后还是自己进去hiredis.h头文件看函数实现才判断出来,233333…

你可能感兴趣的:(C++)