对Hiredis进行了简单封装

1、API进行统一,对外只提供一个接口;

2、屏蔽上层应用对连接的细节处理;

3、底层采用队列的方式保持连接池,保存连接会话;

4、重连时采用时间戳进行控制,每隔一定时间(3s)重连一次,防止频繁重试造成的不必要浪费。

先看一下Hiredis的常用数据结构与API:

//hiredis/hiredis.h
/* Context for a connection to Redis */
typedef struct redisContext {
    int err; /* Error flags, 0 when there is no error */
    char errstr[128]; /* String representation of error when applicable */
    int fd;
    int flags;
    char *obuf; /* Write buffer */
    redisReader *reader; /* Protocol reader */
} redisContext;
/* This is the reply object returned by redisCommand() */
#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
typedef struct redisReply {
    int type; /* REDIS_REPLY_* */
    long long integer; /* The integer when type is REDIS_REPLY_INTEGER */
    int len; /* Length of string */
    char *str; /* Used for both REDIS_REPLY_ERROR and REDIS_REPLY_STRING */
    size_t elements; /* number of elements, for REDIS_REPLY_ARRAY */
    struct redisReply **element; /* elements vector for REDIS_REPLY_ARRAY */
} redisReply;
redisContext *redisConnectWithTimeout(const char *ip, int port, struct timeval tv);
void redisFree(redisContext *c);

封装后的代码:

redis_pool.h

#ifndef __REDIS_POOL_H__
#define __REDIS_POOL_H__
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <memory>
#include <mutex>
#include <queue>
#include <sys/time.h>
#include "hiredis/hiredis.h"
class KGRedisClient
{
public:
    KGRedisClient(std::string ip, int port, std::string password, int timeout = 2000);
    virtual ~KGRedisClient();
 //   bool ExecuteCmd_spop(const char *cmd, size_t len, std::string &response);
  bool ExecuteCmd_spop(std::string &response, const char* format, ...);
 
 //   redisReply* ExecuteCmd(const char *cmd, size_t len);
     redisReply* ExecuteCmd(const char* format, ...);
private:
    int m_timeout;
    int m_serverPort;
    std::string m_setverIp;
 std::string m_password;
 //   CCriticalSection m_lock;
  std::mutex _mutex;
    std::queue<redisContext *> m_clients;
    time_t m_beginInvalidTime;
    static const int m_maxReconnectInterval = 3;
    redisContext* CreateContext();
    void ReleaseContext(redisContext *ctx, bool active);
    bool CheckStatus(redisContext *ctx);
};
#endif
 
 
redis_pool.cpp
 
#include "redis_pool.h"
#include <stdio.h>
KGRedisClient::KGRedisClient(std::string ip, int port, std::string password, int timeout)
{
    m_timeout = timeout;
    m_serverPort = port;
    m_setverIp = ip;
 m_password = password;
    m_beginInvalidTime = 0;
}
KGRedisClient::~KGRedisClient()
{
//    CAutoLock autolock(m_lock);
 std::unique_lock <std::mutex> lck(_mutex);
    while(!m_clients.empty())
    {
        redisContext *ctx = m_clients.front();
        redisFree(ctx);
        m_clients.pop();
    }
}
bool KGRedisClient::ExecuteCmd(std::string &response, const char* format, ...)
{
 va_list args;
 va_start(args, format);
 redisReply *reply = ExecuteCmd(format, args);
 va_end(args);
   
  if(reply == NULL) return false;
    std::shared_ptr<redisReply> autoFree(reply, freeReplyObject);
    if(reply->type == REDIS_REPLY_INTEGER)
    {
        response = std::to_string(reply->integer);
        return true;
    }
    else if(reply->type == REDIS_REPLY_STRING)
    {
        response.assign(reply->str, reply->len);
        return true;
    }
    else if(reply->type == REDIS_REPLY_STATUS)
    {
        response.assign(reply->str, reply->len);
        return true;
    }
    else if(reply->type == REDIS_REPLY_NIL)
    {
        response = "";
        return true;
    }
    else if(reply->type == REDIS_REPLY_ERROR)
    {
        response.assign(reply->str, reply->len);
        return false;
    }
    else if(reply->type == REDIS_REPLY_ARRAY)
    {
        response = "Not Support Array Result!!!";
        return false;
    }
    else
    {
        response = "Undefine Reply Type";
        return false;
    }
}
redisReply* KGRedisClient::ExecuteCmd(const char* format, ...)
{
 va_list args;
 va_start(args, format);
 
 
    redisContext *ctx = CreateContext();
    if(ctx == NULL) return NULL;
  //  redisReply *reply = (redisReply*)redisCommand(ctx, "spop %b", cmd, len);
 //   redisReply *reply = (redisReply*)redisCommand(ctx, "%s", cmd); 
  redisReply* reply = (redisReply*)redisCommand(ctx, format, args);
   va_end(args);
 
    ReleaseContext(ctx, reply != NULL);
    return reply;
}
 
redisContext* KGRedisClient::CreateContext()
{
    {
//        CAutoLock autolock(m_lock);
  std::unique_lock <std::mutex> lck(_mutex);
        if(!m_clients.empty())
        {
            redisContext *ctx = m_clients.front();
            m_clients.pop();
            return ctx;
        }
    }
    time_t now = time(NULL);
    if(now < m_beginInvalidTime + m_maxReconnectInterval) return NULL;
    struct timeval tv;
    tv.tv_sec = m_timeout / 1000;
    tv.tv_usec = (m_timeout % 1000) * 1000;;
    redisContext *ctx = redisConnectWithTimeout(m_setverIp.c_str(), m_serverPort, tv);
    if(ctx == NULL || ctx->err != 0)
    {
        if(ctx != NULL) redisFree(ctx);
        m_beginInvalidTime = time(NULL);
       
        return NULL;
    }
 redisReply *reply;
 std::string strReply = "AUTH ";
 strReply += m_password;
 reply = (redisReply*)redisCommand(ctx, strReply.c_str());
 freeReplyObject(reply);
 reply = NULL;
 printf("connect OK\n");
    return ctx;
}
void KGRedisClient::ReleaseContext(redisContext *ctx, bool active)
{
    if(ctx == NULL) return;
    if(!active) {redisFree(ctx); return;}
//    CAutoLock autolock(m_lock);
 std::unique_lock <std::mutex> lck(_mutex);
    m_clients.push(ctx);
}
bool KGRedisClient::CheckStatus(redisContext *ctx)
{
    redisReply *reply = (redisReply*)redisCommand(ctx, "ping");
    if(reply == NULL) return false;
    std::shared_ptr<redisReply> autoFree(reply, freeReplyObject);
    if(reply->type != REDIS_REPLY_STATUS) return false;
    if(strcasecmp(reply->str,"PONG") != 0) return false;
    return true;
}

成员变量:m_clients用于保存连接池。

成员变量:m_beginInvalidTime、m_maxReconnectInterval 用于控制断掉时的频繁连接。

对外API:ExecuteCmd(const char *cmd, string &response);

redis 连接池 hiredis的更多相关文章

  1. Redis 连接池的问题

      目录 Redis 连接池的问题    1 1.    前言    1 2.解决方法    1     前言 问题描述:Redis跑了一段时间之后,出现了以下异常. Redis Timeout ex ...

  2. 红眼技术博客 » redis连接池红眼技术博客 » redis连接池

    红眼技术博客 » redis连接池 redis连接池

  3. redis连接池操作

    /** * @类描述 redis 工具 * @功能名 POJO * @author zxf * @date 2014年11月25日 */public final class RedisUtil { p ...

  4. java操作redis redis连接池

    redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis. 1.java连接redis java通过需要jedis的jar包获取Jedis连接. jedis-2.8 ...

  5. 三:Redis连接池、JedisPool详解、Redisi分布式

    单机模式: package com.ljq.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; ...

  6. 压测过程中,获取不到redis连接池,发现redis连接数高

    说明:图片截得比较大,浏览器放大倍数看即可(涉及到隐私,打了码,请见谅,如果有疑问,欢迎骚扰). 最近在压测过程中,出现获取不到redis连接池的问题 xshell连接redis服务器,查看连接数,发 ...

  7. Redis连接池

    package com.lee.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; impor ...

  8. Redis】Java中使用Jedis操作Redis(Maven导入包)、创建Redis连接池

    如果我们使用Java操作Redis, 需要确保已经安装了 redis 服务及 Java redis 驱动. Maven项目可以直接在pom.xml中加入jedis包驱动: <!-- https: ...

  9. redis连接池 jedis-2.9.0.jar+commons-pool2-2.4.2.jar

    java使用Redis连接池  jar包为 jedis-2.9.0.jar+commons-pool2-2.4.2.jar jar下载地址 package com.test; import redis ...

随机推荐

  1. How to disable Microsoft Compatibility Telemetry

    Issue: How to disable Microsoft Compatibility Telemetry (CompatTelRunner.exe)?   Option : Disable Mi ...

  2. centos安装pg以及pg配置ssl

    https://blog.csdn.net/iteye_21194/article/details/82645389 https://blog.csdn.net/rudy5348/article/de ...

  3. JSP中三大指令

    JSP指令概述 JSP指令的格式:<%@指令名 attr1=”” attr2=”” %>,一般都会把JSP指令放到JSP文件的最上方,但这不是必须的.  JSP中的指令共有三个:page. ...

  4. springboot中使用拦截器、监听器、过滤器

     拦截器.过滤器.监听器在web项目中很常见,这里对springboot中怎么去使用做一个总结. 1. 拦截器(Interceptor)   我们需要对一个类实现HandlerInterceptor接 ...

  5. appstore跳转

    二维码跳转 https://itunes.apple.com/cn/app/id123123123 应用内跳转 this.alertCtrl.create({ title: '更新', message ...

  6. BZOJ3944 Sum 数论 杜教筛

    原文链接http://www.cnblogs.com/zhouzhendong/p/8671759.html 题目传送门 - BZOJ3944 题意 多组数据(组数<=10). 每组数据一个正整 ...

  7. 044 hive与mysql两种数据源之间的join

    这篇文章是基于上一篇文章的续集 一:需求 1.图形表示 二:程序 1.程序. package com.scala.it import java.util.Properties import org.a ...

  8. HDFS常用API(1)

    一.HDFS集群API所需要jar包的maven配置信息 <dependency> <groupId>org.apache.hadoop</groupId> < ...

  9. HDU-1247 Hat’s Words (暴力)【Trie树】

    <题目链接> 题目大意: 给你一些单词,要求输出将该单词完全分成前.后两个单词之后,若这两个单词都在单词库中出现,则输出该单词. 解题分析: 将每个单词的每一位能够拆分的位置全部暴力枚举一 ...

  10. python 配置导入方式

    许多连接,如 from setting import redis_config pool= redis.ConnectionPool(**redis_config) r=redis.Redis(con ...