数据库_Redis_Windows_C++_01

开发环境

系统:Windows 10 教育版

安装Redis

Redis官网没有提供Windows版本,不过微软团队维护了一个Windows版本[https://github.com/MicrosoftArchive/redis/releases],如下图所示(https://github.com/MicrosoftArchive/redis/releases)。

代码

https://github.com/ysrs/third-party/tree/master/Redis/CPPWindows
代码主要包含两部分,一部分是用于生成hiredis.lib和Win32_Interop.lib的库;另一部分是例子。

#include <hiredis.h>
#include <win32fixes.h>
#include <iostream>
#include <string>


using namespace std;

class Redis
{
public:
    Redis()
    {
        m_pContext = nullptr;
    }

    ~Redis()
    {
        redisFree(m_pContext);
        m_pContext = nullptr;
    }

    bool connect(string host, int port)
    {
        auto bRet = true;
        m_pContext = redisConnect(host.c_str(), port);
        if (m_pContext && m_pContext->err)
        {
            cout << "connect error: " << m_pContext->errstr << endl;
            bRet = false;
        }
        return bRet;
    }

    string get(string key)
    {
        auto pReply = (redisReply*)redisCommand(m_pContext, "GET %s", key.c_str());
        string str = pReply->str;
        freeReplyObject(pReply);
        return str;
    }

    void set(string key, string value)
    {
        redisCommand(m_pContext, "SET %s %s", key.c_str(), value.c_str());
    }

private:
    redisContext* m_pContext;
};


int main()
{
    Redis* r = new Redis();
    if (!r->connect("127.0.0.1", 6379))
    {
        cout << "connect error!" << endl;
        return 0;
    }
    r->set("name", "Hello");
    cout << "Get the name is " << r->get("name").c_str() << endl;
    delete r;

    return 0;
}

运行效果
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值