代码是对redis常见的hash的封装和使用

每个函数都亲自测试过

关于如何安装hiredis模块,网上一搜一大堆,这里不在赘述,如有其他问题欢迎留言交流。

头文件
 

#ifndef REDISBASEMODULE_H
#define REDISBASEMODULE_H
#include <QObject>
#include <QMap>
#include <QVariant>
#include "hiredis/hiredis.h"
#include "redisbasemodule_global.h"
///
/// \brief The RedisBaseModule class
/// 本模块建立Reids链接,封装常用的函数
class REDISBASEMODULESHARED_EXPORT RedisBaseModule
{

public:
    bool getConnect();
    //-----------------HashMap----------------
    int hashHlen(const QString& key);
    redisReply *execommand(QString &command);
    QMap<QString,QVariant> hgetall(QString key);
    RedisBaseModule(const char *ip, const int port);
    bool hmset(QString key, QMap<QString,QVariant> map);
    int hashHexists(const QString& key,const QString& field);
    QString hashHget(const QString& key,const QString& field);
    bool hashHset(const QString &key, const QString &field , const QString& value);
    //-----------------set get----------------
    QString get(const QString &cmmand);
    bool set(const QString &cmmand);
private:
    char* m_ip;
    int m_port;
    redisContext* m_prct;
};

#endif // REDISBASEMODULE_H

cpp

#include "redisbasemodule.h"
#include <QDebug>

RedisBaseModule::RedisBaseModule(const char* ip, const int port)
{
    //memcpy(m_ip,ip,strlen(ip));
    m_port = port;
    m_prct = nullptr;
}

bool RedisBaseModule::getConnect()
{
    struct timeval timeout={2,0};
    m_prct = (redisContext*)redisConnectWithTimeout("10.0.1.70",m_port,timeout);
    if(m_prct == nullptr)
        return false;
    return true;
}
///
/// \brief RedisBaseModule::hmset 同时将多个field-value对设置到哈希表key中
/// \param key 哈希表key
/// \param map 向key中写入的值
/// \return
///
bool RedisBaseModule::hmset(QString key, QMap<QString, QVariant> map)
{
    QString cmd("HMSET ");
    cmd.append(key);
    QMapIterator<QString, QVariant> i(map);
    while (i.hasNext())
    {
        i.next();
        cmd.append(" ");
        cmd.append(i.key());
        cmd.append(" ");
        cmd.append(i.value().toString());
    }
    redisReply * reply = execommand(cmd);
    if(reply == nullptr)
        return false;

    if(QString(QLatin1String(reply->str)) == "OK")
        return true;

    return false;
}
///
/// \brief RedisBaseModule::hashHexists 判断哈希表中的某个字段是否存在
/// \param key
/// \param field
/// \return 存在返回1 不存在返回0
///
int RedisBaseModule::hashHexists(const QString &key, const QString &field)
{
    int result = 0;
    QString cmd("HEXISTS ");
    cmd.append(key);
    cmd.append(" ");
    cmd.append(field);
    redisReply* reply =(redisReply*)redisCommand(m_prct,cmd.toStdString().c_str());
    if(reply->type == REDIS_REPLY_INTEGER)
        result = reply->integer;
    freeReplyObject(reply);
    return result;
}
///
/// \brief RedisBaseModule::hashHget
/// \param key   返回哈希表 key
/// \param field 中给定域 field 的值
/// \return 成功返回给定的域,否则NULL
///
QString RedisBaseModule::hashHget(const QString &key, const QString &field)
{
    QString tmp("");
    QString cmd("HGET ");
    cmd.append(key);
    cmd.append(" ");
    cmd.append(field);
    QByteArray buff = cmd.toLatin1();
    redisReply* reply =(redisReply*)redisCommand(m_prct,buff.data());
    if(reply->type == REDIS_REPLY_STRING)
        tmp = reply->str;
    freeReplyObject(reply);
    return tmp;
}
///
/// \brief RedisBaseModule::hashHset 修改哈希表中某个字段的值
/// \param key    hash的Key
/// \param field  key中的某个字段
/// \param value  想要写入的新值
/// \return true field之前不存在  之前存在值被覆盖
///
bool RedisBaseModule::hashHset(const QString &key, const QString &field, const QString &value)
{
    int result=0;
    QString cmd("HSET ");
    cmd.append(key);
    cmd.append(" ");
    cmd.append(field);
    cmd.append(" ");
    cmd.append(value);
    redisReply * reply = execommand(cmd);
    if(reply->type == REDIS_REPLY_INTEGER)
        result += reply -> integer;
    freeReplyObject(reply);
    return result !=0?true:false;
}

QString RedisBaseModule::get(const QString &cmmand)
{
    QString cmd("GET ");
    QString s("");
    cmd.append(cmmand);
    redisReply * reply = execommand(cmd);
    if(reply->type == REDIS_REPLY_STRING)
        s = reply->str;
    freeReplyObject(reply);
    return s;
}

bool RedisBaseModule::set(const QString &cmmand)
{
    QString cmd("SET ");
    QString s("");
    cmd.append(cmmand);
    redisReply * reply = execommand(cmd);
    if(reply->type == REDIS_REPLY_STRING)
        s = reply->str;
    freeReplyObject(reply);
    if(s == "OK")
        return true;
    return false;

}
///
/// \brief RedisBaseModule::execommand 指令执行的终极入口
/// \param command  命令语句
/// \return
///
redisReply *RedisBaseModule::execommand(QString &command)
{
    if(m_prct == nullptr)
        return nullptr;
    QByteArray buff = command.toLatin1();

     redisReply* reply =(redisReply*)redisCommand(m_prct,buff.data());
     qDebug()<<"comand:"<<command;
     if(reply == nullptr)
     {
         freeReplyObject(reply);
         return nullptr;
     }
     else
         return reply;
}
///
/// \brief RedisBaseModule::hgetall 根据hash的key 获取里面所有的键值对,并以map的形式返回
/// \param key   hash的key
/// \return
///
QMap<QString, QVariant> RedisBaseModule::hgetall(QString key)
{
    QString cmd("HGETALL ");
    cmd.append(key);

    redisReply* reply = execommand(cmd);
    QString k,v;
    QMap<QString,QVariant> keypairs;
    if(reply->type == REDIS_REPLY_ARRAY)
    {
        for(uint j = 0 ; j< reply->elements;j++)
        {
            k = reply->element[j]->str;
            v = hashHget(key,reply->element[j]->str);
            keypairs.insert(k,v);
            j++;
        }
        freeReplyObject(reply);
    }
    return keypairs;
}
///
/// \brief RedisBaseModule::hashHlen 返回哈希表中域的数量
/// \param key
/// \return count of hash
///
int RedisBaseModule::hashHlen(const QString &key)
{
    int result = 0;
    QString cmd("HLEN ");
    cmd.append(key);
    redisReply* reply = execommand(cmd);
    if(reply->type == REDIS_REPLY_INTEGER)
    {
        result = reply->integer;
    }
    return result;
}

测试

p_r = new RedisBaseModule("10.0.1.70",6379);
    qDebug()<<p_r->getConnect();
    QMap<QString ,QVariant > cmd;
    cmd.insert("name","korol");
    cmd.insert("age",16);
    cmd.insert("user","root");
    cmd.insert("password","orange");
    qDebug()<<p_r->hmset("RedisModuleTest",cmd);
    qDebug()<<p_r->hgetall("RedisModuleTest");
    qDebug()<<p_r->hashHexists("RedisModuleTest","name1");
    qDebug()<<p_r->hashHlen("RedisModuleTest");
    qDebug()<<p_r->hashHset("RedisModuleTest","phone","21");
    qDebug()<<p_r->hashHset("RedisModuleTest","address","判断哈希表中的某个字段是否存在");

 

Logo

华为云1024程序员节送福利,参与活动赢单人4000元礼包,更有热门技术干货免费学习

更多推荐