在C++中使用Hiredis庫連接Redis服務器的步驟如下:
#include <hiredis/hiredis.h>
redisContext *context = redisConnect("127.0.0.1", 6379);
if (context == NULL || context->err) {
if (context) {
printf("Error: %s\n", context->errstr);
redisFree(context);
} else {
printf("Cannot allocate redis context\n");
}
return -1;
}
這里將連接到本地Redis服務器,如果連接失敗,會輸出錯誤信息并返回-1。
redisReply *reply = (redisReply *)redisCommand(context, "SET key value");
if (reply == NULL) {
printf("Error executing command\n");
return -1;
}
printf("Command executed successfully\n");
freeReplyObject(reply);
這里執(zhí)行了一個SET操作,將key設置為value。
redisFree(context);
這樣就完成了通過Hiredis庫連接到Redis服務器并執(zhí)行命令的過程。在實際使用中,你可以根據(jù)需要執(zhí)行其他操作,如GET、DEL等。