栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ubuntu中使用QT、C++使用redis、hiredis记录

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ubuntu中使用QT、C++使用redis、hiredis记录

ubuntu中使用QT、C++使用redis、hiredis记录

参考:

https://blog.csdn.net/qq78442761/article/details/103084824
https://blog.csdn.net/MoriingRain/article/details/115742181

本机环境
ubuntu20.04

一、安装redis

这一部分参考:菜鸟教程-redis安装

二、安装hiredis

C++调用redis需要配合hiredis一起使用,因此需要事先安装hiredis。
1.下载hiredis包

git clone https://github.com/redis/hiredis
2.进入hiredis文件夹

在hiredis文件夹下开启终端,并输入

make
sudo make install

三、在QT中配置hiredis

1.新建项目

2.Pro文件添加hiredis

INCLUDEPATH += /home/cj/redis/hiredis
LIBS += -L /usr/local/lib -lhiredis
HEADERS += /home/cj/redis/hiredis/adapters/qt.h

1).INCLUDEPATH += 中这个地址写入你前面下载hiredis的安装包位置


2)LIBS +=这个地方写入hiredis安装位置

3)HEADERS += 这个将qt.h加入

3.测试代码
在main.cpp文件中写入

#include 
#include 
#include 

void getCallback(redisAsyncContext *ctx, void *r, void *privdata){

    qDebug() << "getCallback called";

    redisReply *reply = static_cast(r);
    if(reply == nullptr){

        qDebug() << "The reply is nullptr";
        return;
    }

    qDebug() << "result: ";

    for(int i = 0; i < reply->elements; i++){

        qDebug() << "key: " << reply->element[i]->str;
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    redisAsyncContext *ctx = redisAsyncConnect("127.0.0.1", 6379);

    RedisQtAdapter adapter;

    if(ctx->err){

        qDebug()<< "error: " << ctx->errstr;
        redisAsyncFree(ctx);
        return 0;
    }
    adapter.setContext(ctx);

    redisAsyncCommand(ctx, nullptr, nullptr, "auth xxxxxxxxx");
    redisAsyncCommand(ctx, getCallback, nullptr, "KEYS *");
    qDebug() << "over";

    return a.exec();
}

运行结果

四、C++直接使用hiredis

编辑器依旧使用QT
1.建立纯C++项目

2.修改pro文件
加入:

LIBS += -L /usr/local/lib -lhiredis


3.main.cpp

#include 
#include 
#include 
#include 

int main()
{
    redisContext * rc = redisConnect("127.0.0.1",6379);
    assert(rc != NULL);

    char* com = "hmset user name jack age 18 sex male height 180";
    redisReply* res =(redisReply*)redisCommand(rc,com);

    if(res->type == REDIS_REPLY_STATUS)
    {
        printf("Success %sn",res->str);
    }
    else
        printf("failn");

    com = "hgetall user";
    res = (redisReply*)redisCommand(rc,com);
    if(res->type == REDIS_REPLY_ARRAY)
    {
        for(int i = 0; i < res->elements; i++)
        {
            if(i%2 != 0)
                printf("%sn",res->element[i]->str);
            else
                printf("%s",res->element[i]->str);
        }
    }
    else if(res->type == REDIS_REPLY_STRING)
    {
        printf("%s",res->str);
    }

    freeReplyObject(res);
    redisFree(rc);
    return 1;
}


效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/982139.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号