redisplusplus笔记

redis与连接

redisplusplus笔记_第1张图片
connection主要方法及与reply关系
redisplusplus笔记_第2张图片
recv使用ReplyUPtr,即unique_ptr,其中ReplyDeleter定义如下

struct ReplyDeleter {
    void operator()(redisReply *reply) const {
        if (reply != nullptr) {
            freeReplyObject(reply);
        }
    }
};

其调用redisGetReply获取响应,当中会处理以下几种异常情况

  • redisGetReply返回不是REDIS_OK,抛出异常
  • 调用broken判断连接是否断了
  • 在handle_error_reply标识为true,并且响应的type值为REDIS_REPLY_ERROR,抛出异常

send方法主要是调用redisAppendCommandArgv,会处理下面情况

  • redisAppendCommandArgv如果失败,会抛出异常
  • 调用broken()看连接是否断了
   bool broken() const noexcept {
        return !_ctx || _ctx->err != REDIS_OK;
    }

解析响应

通过模板函数来作具体类型的的解析转发

template <typename T>
inline T parse(redisReply &reply) {
    return parse(ParseTag<T>(), reply);
}

optional解析

template <typename T>
Optional<T> parse(ParseTag<Optional<T>>, redisReply &reply) {
    if (reply::is_nil(reply)) {
        // Because of a GCC bug, we cannot return {} for -std=c++17
        // Refer to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86465
#if defined REDIS_PLUS_PLUS_HAS_OPTIONAL
        return std::nullopt;
#else
        return {};
#endif
    }

    return Optional<T>(parse<T>(reply));
}

字符串解析

std::string parse(ParseTag<std::string>, redisReply &reply) {
#ifdef REDIS_PLUS_PLUS_RESP_VERSION_3
    if (!reply::is_string(reply) && !reply::is_status(reply)
            && !reply::is_verb(reply) && !reply::is_bignum(reply)) {
        throw ParseError("STRING or STATUS or VERB or BIGNUM", reply);
    }
#else
    if (!reply::is_string(reply) && !reply::is_status(reply)) {
        throw ParseError("STRING or STATUS", reply);
    }
#endif

    if (reply.str == nullptr) {
        throw ProtoError("A null string reply");
    }

    // Old version hiredis' *redisReply::len* is of type int.
    // So we CANNOT have something like: *return {reply.str, reply.len}*.
    return std::string(reply.str, reply.len);
}

设计点

  • 在redis层使用函数作为模板类型参数,也就是command层定义的函数。
  • 使用可变参数模板
  • 在redis层最终会调用不带连接的command方法,调用带连接参数的_command方法(调用command层具体的函数,然后接收响应)

你可能感兴趣的:(redis,笔记)