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 <QCoreApplication>
#include <adapters/qt.h>
#include <QDebug>
void getCallback(redisAsyncContext *ctx, void *r, void *privdata){
qDebug() << "getCallback called";
redisReply *reply = static_cast<redisReply*>(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 <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <hiredis/hiredis.h>
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 %s\n",res->str);
}
else
printf("fail\n");
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("%s\n",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;
}
效果