一個簡單的RedisDemo

// 一個簡單的Windows版本Redis Demo, 
// Create on 2022.01.11, by zdleek

////可能需要包含的redis頭文件相對路徑如下
//$(SolutionDir)..\deps\hiredis;

//$(SolutionDir)..\deps\linenoise;

//$(SolutionDir)..\deps\lua\src

//////////////////////////////////////////////////////


#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);
}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章