github 下载:https://github.com/redis/hiredis
解压后,直接cmake ,我这种弱鸡直接用cmake gui了
直接编译不会报错,(C++圈里的库已经越来越人性化,不像往年编译个库报错一堆各种坑)
生成lib直接使用
因为是静态库了 他源码是依赖socketlib的,所以要在你的项目里也加上这句
#pragma comment(lib,"ws2_32.lib")
以下是测试代码:
// redis_test.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include "hiredis.h"
#include <string>
#pragma comment(lib,"hiredisd.lib")
#pragma comment(lib,"ws2_32.lib")
using namespace std;
bool publishMessage(redisContext* conn, const char* channel, const char* message) {
redisReply* reply = (redisReply*)redisCommand(conn, "PUBLISH %s %s", channel, message);
if (reply && reply->type == REDIS_REPLY_INTEGER && reply->integer > 0) {
freeReplyObject(reply);
return true;
}
freeReplyObject(reply);
return false;
}
void subscribeChannel(redisContext* conn, const char* channel) {
redisReply* reply = (redisReply*)redisCommand(conn, "SUBSCRIBE %s", channel);
freeReplyObject(reply);
while (redisGetReply(conn, (void**)&reply) == REDIS_OK) {
if (reply->type == REDIS_REPLY_ARRAY && reply->elements >= 3 && strcmp(reply->element[0]->str, "message") == 0) {
std::cout << "Received message: " << reply->element[2]->str << std::endl;
}
freeReplyObject(reply);
}
}
int main()
{
redisContext *conn = redisConnect("127.0.0.1", 6379);
if (conn->err || conn ==NULL)
{
cout << "链接失败" << endl;
}
else
{
cout << "成功" << endl;
}
string mypass = "yourpassword";
//根据密码登录
redisReply* m_pReply = (redisReply*)redisCommand(conn, "AUTH %s", mypass.c_str());
if (!m_pReply)
{
cout << "redis exe failed!!" << endl;
return false;
}
if (!(m_pReply->type == REDIS_REPLY_STATUS && strcmp(m_pReply->str, "OK") == 0))
{
cout << " redis auth failed!!!!" << endl;
freeReplyObject(m_pReply);
m_pReply = NULL;
return false;
}
/*
redisReply* reply = (redisReply*)redisCommand(conn, "SET xxx xiaxiaomo");
freeReplyObject(reply);
reply = (redisReply*)redisCommand(conn, "get xxx");
printf("%s\n", reply->str);
freeReplyObject(reply);
redisFree(conn);
return 0;*/
// 发布消息
std::string channel = "youer_message";
std::string message = "Hello, C++!";
if (publishMessage(conn, channel.c_str(), message.c_str())) {
std::cout << "Message published successfully." << std::endl;
}
else {
std::cout << "Failed to publish message." << std::endl;
}
// 订阅消息
//subscribeChannel(conn, channel.c_str());
// 关闭Redis连接
redisFree(conn);
}
拜拜~