redis數據存儲--C++連接redis


一、下載的是Redis Windows版本;下載地址:https://github.com/microsoftarchive/redis;解壓到:E:\Software\redis-3.0;

二、用VS打開項目:

  1. 打開文件E:\Software\redis-3.0\msvs;點擊RedisServer.sln,用VS打開;所有警告點擊確定,如下圖:這里使用的是VS2015

    

  2. 運行所有解決方案:

    加載項目后如圖:

    

 

     右擊解決方案,選擇重新生成解決方案,解決方案生成成功

    

 

  3. 打開文件E:\Software\redis-3.0\msvs\x64\Debug,查看生成的lib和exe

    

 

 三、 新建項目TestRedis

  1. 添加包含目錄,點擊TestRedis項目,右鍵屬性->C/C++->常規->附加包含目錄,輸入以下兩個目錄,以“;”號分隔開:

    A、添加Redis庫原碼, 路徑:E:\Software\redis-3.0\src;

    B、添加HiRedis庫原碼,路徑:E:\Software\redis-3.0\deps\hiredis;

  2. 添加附加依賴庫:hiredis.lib,Win32_Interop.lib;點擊TestRedis項目,右鍵屬性->鏈接器->輸入->附加依賴項輸入庫所在目錄;

  3.重新啟動Redis-server, 打開CMD,導航到Redis-server目錄,輸入,如下

 

    

四,添加TestRedis項目,嘗試連接

#include "stdafx.h"
#include <Windows.h>
#include <hiredis.h>

#pragma comment(lib, "Win32_Interop.lib")
#pragma comment(lib, "hiredis.lib")

int main()
{
    //redis默認監聽端口為6387 可以再配置文件中修改 
    redisContext* pRedisContext = redisConnect("127.0.0.1", 6379);
    if (NULL == pRedisContext || pRedisContext->err)
    {
        printf("%s \r\n", pRedisContext->errstr);
        printf("Connect to redis server failed \n");
        return -1;
    }

    //輸入Redis密碼
    const char *pszRedisPwd = "123456";
    redisReply *pRedisReply = (redisReply*)redisCommand(pRedisContext, "AUTH %s", pszRedisPwd);
    if (NULL != pRedisReply)
    {
        freeReplyObject(pRedisReply);
    }
    //用get命令獲取數據
    char szRedisBuff[256] = { 0 };
    sprintf_s(szRedisBuff, "GET %s", "name");
    pRedisReply = (redisReply*)redisCommand(pRedisContext, szRedisBuff);
    if (NULL == pRedisReply)
    {
        printf("Get data Error!");
        return -1;
    }

    if (NULL == pRedisReply->str)
    {
        freeReplyObject(pRedisReply);
        return -1;
    }

    string strRes(pRedisReply->str);
    freeReplyObject(pRedisReply);

    //向Redis寫入數據
    pRedisReply = (redisReply *)redisCommand(pRedisContext, "SET keyName huantest");
    if (NULL != pRedisReply)
    {
        freeReplyObject(pRedisReply);
    }

    return 0; }

 

 注意:Redis Windows截止作者使用的時間:

  1. 最新版本為 3.0, 3.0的Window版本在使用redisConnectWithTimeout的方法時會出現連接錯誤:報磁盤空間不足;

  2. 如果vs環境下沒有庫文件ShLwApi.Lib,AdvAPI32.Lib,會報錯;這兩個庫文件在C盤下,請自行搜索;

 

    

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM