Hiredis浅尝


前言

如何在C++中使用Hiredis客户端操作Redis,略过服务端配置,本文仅讲解Hiredis接口使用步骤


提示:以下是本篇文章正文内容,下面案例可供参考

一、HiRedis是什么?

Hiredis库封装了Redis的C语言接口,用来操作Redis服务端

二、使用步骤

1.源文件

Hiredis源码
Redis使用文档

2.基础API

//建立 Redis Server 连接
    redisContext *redisConnectWithOptions(const redisOptions *options);
    redisContext *redisConnect(const char *ip, int port);
    redisContext *redisConnectWithTimeout(const char *ip, int port, const struct timeval tv);
    redisContext *redisConnectNonBlock(const char *ip, int port);
    redisContext *redisConnectBindNonBlock(const char *ip, int port,
                                           const char *source_addr);
    redisContext *redisConnectBindNonBlockWithReuse(const char *ip, int port,
                                                    const char *source_addr);
    redisContext *redisConnectUnix(const char *path);
    redisContext *redisConnectUnixWithTimeout(const char *path, const struct timeval tv);
    redisContext *redisConnectUnixNonBlock(const char *path);
    redisContext *redisConnectFd(redisFD fd);

//断开 Redis Server 的连接(关闭 Socket)并释放 redisContext 结构体所占用的内存
    void redisFree(redisContext *c);
//释放 redisReply 指针变量所占用的内存,freeReplyObject() 会递归的释放数组中的资源,不需要手动释放数组资源
    void freeReplyObject(void *reply);

三、最小用例

#define LOCAL_HOST "127.0.0.1" //默认ID
#define PORT 6379 //默认端口
using ExecCommandCB = std::function<bool(redisReply *)>; 
class HiRedisManager{
		
        public:
            HiRedisManager(){
                Connect();
            }
            
            ~HiRedisManager(){
                DisConnect();
            }
            
            bool ExecCommand(const ExecCommandCB & cb, const char * format, ...){
                std::lock_guard<std::recursive_mutex> lockGuard(mutex_);
                va_list va;
                va_start(va, format);
                redisReply * reply = (redisReply *)redisvCommand(redis_context_, format, va);
                va_end(va);
                if(reply == NULL){
                    ShowErrDetails();
                    return false;
                }
                bool cb_ret = cb(reply);
                Free(reply);
                return cb_ret; 
            }

            void ShowErrDetails(){
                SPDLOG_INFO("errstr:{}, errType:{}", redis_context_->errstr, redis_context_->err);
                DisConnect();
                Connect();
            }

			bool StroeHashValue(const std::string & hash_name, const std::string & key, std::string & value){
                ExecCommandCB cb = [](redisReply * reply) -> bool{
                    return true;
                };
                return ExecCommand(cb, "HSET %s %s %s", hash_name.c_str(), key.c_str(), value.c_str()); 
            }  

            bool GetHashValue(const std::string & hash_name, const std::string & key, std::string & value){
                ExecCommandCB cb = [&value](redisReply * reply) -> bool{
                    if(reply->len <=0 ){
                        return false;
                    }
                    value = reply->str;
                    return true;
                };
                return ExecCommand(cb, "HGET %s %s", hash_name.c_str(), key.c_str()); 
            }


        protected:
            bool Connect(){
                std::lock_guard<std::recursive_mutex> lockGuard(mutex_);
                struct timeval timeout = {2};
                redis_context_ = redisConnectWithTimeout((char*)LOCAL_HOST, PORT, timeout);
                if(!redis_context_){
                    SPDLOG_ERROR("redis connect fail redis_context_ null");
                    return false;
                }
                if(redis_context_->err){
                    SPDLOG_ERROR("redis connect fail Error:{}", redis_context_->errstr);
                    DisConnect();
                    return false;
                }
                SPDLOG_INFO("redis connect success");
                return true;
            }

            void DisConnect(){
                std::lock_guard<std::recursive_mutex> lockGuard(mutex_);
                if(redis_context_){
                    redisFree(redis_context_);
                    redis_context_ = NULL;
                    SPDLOG_ERROR("redis disconnect");
                }
            }

            void Free(redisReply *reply){
                if(reply){
                    freeReplyObject(reply);
                    reply = NULL;
                }
            }

        private:
        redisContext *redis_context_; //非线程安全
        std::recursive_mutex mutex_;

};

最近刚接触Redis,记录个人的使用方式,欢迎留言指出问题!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值