redis - 空格引起的bug

项目需要,使用redis把数据存储到内存。加快数据访问。
封装了redis的 set 和 get 的接口,代码如下:

//修正这个bug的代码如下:
int CRedisApi::Get(const std::string& strKey, std::string& strValue)
{
    std::string cmd = "get " + m_GetKey(strKey);
    redisReply *reply = m_GetReply(cmd.c_str());;

    CHECK_REDIS_REPLY(reply)

    int iRet = 0;
    if (reply->type == REDIS_REPLY_STRING) {
        strValue = reply->str;
        strValue = m_StringRecoverSpace(strValue);
    } else if (reply->type == REDIS_REPLY_NIL) {
        strValue.clear();
    } else if (reply->type == REDIS_REPLY_ERROR) {
        m_sLastErrMsg = reply->str ? reply->str : " ";
        iRet = ERR_REDIS_REPLY;
    } else {
        m_sLastErrMsg = "redis reply type not match";
        iRet = ERR_REDIS_REPLY_TYPE_NOT_MATCH;
    }

    freeReplyObject(reply);
    return iRet;
}

//#include 
int CRedisApi::Set(const std::string& strKey, const std::string& strValue, int iTtl)
{
    std::string cmd = "set " + m_GetKey(strKey) + " "+ m_StringReplaceSpace(strValue);
    /*char *szFile = "/home/appadmin/sunny/1111.log";
    char  cMode = 'a';
    FILE * file = fopen(szFile, &cMode);
    if (file != NULL)
    {
        fwrite(cmd.c_str(), 1, cmd.length()+1, file);
        char *szDel = "\n";
        fwrite(szDel, 1, 1, file);
        fclose(file);
    }*/
    redisReply *reply = m_GetReply(cmd.c_str());

    CHECK_REDIS_REPLY(reply)

    if (reply->type == REDIS_REPLY_STATUS && strcasecmp(reply->str, "OK") == 0) {
        freeReplyObject(reply);
        if (iTtl > 0) {
            return Expire(strKey, iTtl);
        } else {
            return 0;
        }
    } else if (reply->type == REDIS_REPLY_ERROR) {
        freeReplyObject(reply);
        if (reply->len > 0 && reply->str) {
            m_sLastErrMsg = reply->str;
        }
        return ERR_REDIS_REPLY;
    }

    return 0;
}

redisReply* CRedisApi::m_GetReply(const char *cmd)
{
    redisReply *reply = NULL;
    while (m_iContexId < m_vecRedisContext.size()) {
        reply = (redisReply *)redisCommand(m_vecRedisContext[m_iContexId], cmd);
        if (reply != NULL) {
            return reply;
        }
        ++m_iContexId;
    }
    m_iContexId = 0;
    if (Connect() >= 0) {
        for (int i = 0; i < (int)m_vecRedisContext.size(); ++i) {
            reply = (redisReply *)redisCommand(m_vecRedisContext[i], cmd);
            if (reply != NULL) {
                return reply;
            }
        }
        return NULL;
    }

    return 0;
}

bug出现 - 如果Set() 函数中形参 strValue 包含空格,虽然Set() 正确的返回,但redis内存中没有设置值。

redis - 空格引起的bug_第1张图片

redis - 空格引起的bug_第2张图片
redis - 空格引起的bug_第3张图片
redis - 空格引起的bug_第4张图片
redis - 空格引起的bug_第5张图片
redis - 空格引起的bug_第6张图片

你可能感兴趣的:(redis)