首先需要有redis的库文件和头文件,如果没有可以参考前一篇文章Windows下使用c++编译hiredis.lib,Win32_Interop.lib_没有网名L的博客-CSDN博客
进行编译生成。
生成后需要将头文件和.lib文件导入到项目中。
打开项目属性,点击VC++目录进行设置。
第一步,在包含目录下把hredis.h位置的目录路径加入,也可直接将hredis.h加入到项目中,这里使用的是绝对路径。
第二步,将hiredis.lib,Win32_Interop.lib库文件放入项目的库文件之中,plotbase.lib为博主需要用的,跟redis无关。
第三步,在vc++目录的库目录下加入改路径。
第四步,在链接器中的输入,附加依赖库中加入库文件。
配置完成即可开始使用
#pragma once
#include "hiredis.h"
//对redis进行操作的类
class CRedisOperation
{
public:
CRedisOperation();
~CRedisOperation();
public:
void doTest();
};
#include "RedisOperation.h" #include#include #include #include #include #include #include "hiredis.h" //构造函数 CRedisOperation::CRedisOperation() { } //析构函数 CRedisOperation::~CRedisOperation() { } //测试函数 void CRedisOperation::doTest() { //连接redis 需要启动才可以进行连接 //redis默认监听端口为6387 可以再配置文件中修改 redisContext* c = redisConnect("127.0.0.1", 6379); if (c->err) { printf("Connect to redisServer faile:%sn", c->errstr); redisFree(c); return; } printf("Connect to redisServer Successn"); //为redis设置key const char* command1 = "set stest1 value1"; //执行redis命令行 redisReply * r = (redisReply *) redisCommand(c, command1); //如果返回NULL则说明执行失败 if (NULL == r) { printf("Execut command1 failuren"); redisFree(c); return; } //如果执行失败则释放连接 if (!(r->type == REDIS_REPLY_STATUS && (strcmp(r->str, "OK") == 0 || strcmp(r->str, "ok") == 0))) { printf("Failed to execute command[%s]n", command1); freeReplyObject(r); redisFree(c); return; } //执行成功 释放redisCommand执行后返回的redisReply所占用的内存 freeReplyObject(r); printf("Succeed to execute command[%s]n", command1); const char * command2 = "strlen stest1"; r = (redisReply *) redisCommand(c, command2); //如果返回类型不是整形 则释放连接 if (r->type != REDIS_REPLY_INTEGER) { printf("Failed to execute command[%s]n", command2); freeReplyObject(r); redisFree(c); return; } //获取字符串长度 int length = r->integer; freeReplyObject(r); printf("The length of 'stest1' is %d.n", length); printf("Succeed to execute command[%s]n", command2); //获取redis键值对信息 const char * command3 = "get stest1"; r = (redisReply *) redisCommand(c, command3); if (r->type != REDIS_REPLY_STRING) { printf("Failed to execute command[%s]n", command3); freeReplyObject(r); redisFree(c); return; } printf("The value of 'stest1' is %sn", r->str); freeReplyObject(r); printf("Succeed to execute command[%s]n", command3); const char * command4 = "get stest2"; r = (redisReply *) redisCommand(c, command4); if (r->type != REDIS_REPLY_NIL) { printf("Failed to execute command[%s]n", command4); freeReplyObject(r); redisFree(c); return; } freeReplyObject(r); printf("Succeed to execute command[%s]n", command4); //释放连接资源 redisFree(c); }



