一个简单的RedisDemo

// zdRedisDemo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// 一个简单的Redis Demo
// Create on 2022.01.11, by zdleek
//


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

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

using namespace std;

void FloatDemo();
int SimpleRedisDemo();

int main()
{
    std::cout << "Hello World!\nThis is zd Redis demo!\n" << std::endl;
    
    SimpleRedisDemo();

    FloatDemo();//for test only

    system("pause");
    return 0;
}

int SimpleRedisDemo()
{
    //redis默认监听端口为6379 可以在配置文件中修改 
    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;
    }
    printf("Connect to redis server success \n");

    //输入Redis密码
    const char* pszRedisPwd = "123456";
    redisReply* pRedisReply = (redisReply*)redisCommand(pRedisContext, "AUTH %s", pszRedisPwd);
    if (NULL != pRedisReply)
    {
        freeReplyObject(pRedisReply);
    }

    //向Redis写入数据
    pRedisReply = (redisReply*)redisCommand(pRedisContext, "SET TestKey1 Value4Test1");
    printf("Send command to Redis: SET TestKey1 Value4Test1\r\n");
    if (NULL != pRedisReply)
    {
        freeReplyObject(pRedisReply);
    }
    else
    {
        printf("Set TestKey1 value fail!\r\n");
        return -1;
    }

    //用get命令获取数据
    char szRedisBuff[256] = { 0 };
    sprintf_s(szRedisBuff, "GET %s", "TestKey1");
    printf("Send command to Redis: %s\r\n", szRedisBuff);
    pRedisReply = (redisReply*)redisCommand(pRedisContext, szRedisBuff);
    if (NULL == pRedisReply)
    {
        printf("Get data Error!");
        return -1;
    }

    if (NULL == pRedisReply->str)
    {
        freeReplyObject(pRedisReply);
        return -1;
    }
    printf("Get the Result:%s\r\n", pRedisReply->str);

    string strRes(pRedisReply->str);
    freeReplyObject(pRedisReply);
    return 0;
}

//浮点数测试
void FloatDemo()
{
    //Redis中浮点数无限大小的表示如下
    double R_Zero = 0.0;
    double R_PosInf = 1.0 / R_Zero;
    double R_NegInf = -1.0 / R_Zero;
    double R_Nan = R_Zero / R_Zero;

    printf("\nFloat infinity demo:\nR_Zero, R_PosInf, R_NegInf, R_Nan \n%lf,  %lf,  %lf,  %lf\n", 
        R_Zero, R_PosInf, R_NegInf, R_Nan);

    //浮点数比较
    double a = 1.0;
    double b = 1.0;
    if (a - b == R_NegInf) {
        printf("%lf - %lf != 0\n", a, b);
    }
    else {
        printf("%lf - %lf == 0\n", a, b);
    }

}

原文地址:https://www.cnblogs.com/Andrewz/p/15789493.html