对hiredis接口的封装

本文详细介绍了如何对hiredis库的接口进行封装,旨在提供更方便的使用体验。通过阅读,读者将了解如何在自己的项目中整合并自定义hiredis的功能,以实现高效的数据交互。
摘要由CSDN通过智能技术生成

tg_redis.h

#ifndef TG_REDIS_H
#define TG_REDIS_H

#include <stdio.h>
#include <stdarg.h>
#include <hiredis/hiredis.h>
#include"string"
#include<string.h>
#include<memory>
#include<vector>

struct tg_redis_param
{
    std::string host;
    int port;
    int db_index;
    std::string pwd;
    struct timeval timeout;
};

class tg_redis_result
{
private:
    redisReply* _reply;

public:
    tg_redis_result(redisReply* reply):_reply(reply)
    {
    }

    ~tg_redis_result()
    {
        if(_reply)
        {
            freeReplyObject(_reply);
            _reply=nullptr;
        }
    }

public:
    bool is_null()
    {
        return !_reply || _reply->type == REDIS_REPLY_NIL;
    }

    bool is_error()
    {
        return _reply->type == REDIS_REPLY_ERROR;
    }

    bool is_ok()
    {
        return !is_null() && !is_error();
    }

    const redisReply* get_reply()
    {
        return _reply;
    }

    bool try_get_value(int64_t& out_val)
    {
        if(is_error())
        {
            return false;
        }

        out_val = std::atoll(_reply->str);
        return true;
    }

    bool try_get_value(double& out_val)
    {
        if(is_error())
        {
            return false;
        }

        out_val = std::atof(_reply->str);
        return true;
    }

    bool try_get_value(std::string& out_val)
    {
        if(is_error())
        {
            return false;
        }

        out_val = _reply->str;
        return true;
    }

    bool try_get_value(bool& out_val)
    {
        if(is_error())
        {
            return false;
        }

        out_val = strcasecmp("true", _reply->str) == 0;
        return true;
    }

    uint64_t get_len()
    {
        return _reply->len;
    }

    bool is_arr()
    {
        return _reply->type == REDIS_REPLY_ARRAY;
    }

    uint64_t get_len_arr()
    {
        return _reply->elements;
    }

    int64_t get_integer()
    {
        return _reply->integer;
    }

    const char* get_str()
    {
        return _reply->str;
    }
};

clas
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值