本文記錄如何用 C++ 操作 Redis 資料庫。做法是直接呼叫官方提供的 hiredis 接口,目前僅支援 Linux 環境。hiredis 原始碼可從 https://github.com/redis/hiredis 取得。
1. redisContext* redisConnect(const char *ip, int port)
用來建立連線,兩個參數分別是 IP 與埠號(Redis 預設為 6379)。另有 redisConnectWithTimeout(const char *ip, int port, timeval tv) 可設定連線逾時。
2. void *redisCommand(redisContext *c, const char *format, ...)
執行 Redis 命令。第一個參數是 redisConnect 回傳的連線物件,其後為不定參數,用法與 C 語言的 printf 相同。回傳值為 void*,實務上通常強制轉型為 redisReply* 再做處理。
3. void freeReplyObject(void *reply)
釋放 redisCommand 回傳的 redisReply 所佔記憶體。
4. void redisFree(redisContext *c)
關閉 redisConnect 建立的連線。
下載 hiredis.tar.gz 並解壓,裡面有 Makefile,執行 make 即可編譯。接著把 libhiredis.so 複製到 /usr/local/lib/,把 hiredis.h 複製到 /usr/local/include/hiredis/;也可以直接執行 make install 讓它自動完成。
之後在程式中包含 #include <hiredis/hiredis.h> 就能使用。
為了使用方便,通常會包一層薄封裝,方法依專案需求增減。
redis.h
#ifndef _REDIS_H_
#define _REDIS_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <hiredis/hiredis.h>
class Redis
{
public:
Redis() {}
~Redis()
{
this->_connect = NULL;
this->_reply = NULL;
}
bool connect(std::string host, int port)
{
this->_connect = redisConnect(host.c_str(), port);
if (this->_connect != NULL && this->_connect->err)
{
printf("connect error: %s\n", this->_connect->errstr);
return 0;
}
return 1;
}
std::string get(std::string key)
{
this->_reply = (redisReply*)redisCommand(this->_connect, "GET %s", key.c_str());
std::string str = this->_reply->str;
freeReplyObject(this->_reply);
return str;
}
void set(std::string key, std::string value)
{
redisCommand(this->_connect, "SET %s %s", key.c_str(), value.c_str());
}
private:
redisContext* _connect;
redisReply* _reply;
};
#endif // _REDIS_H_
redis.cpp
#include "redis.h"
int main()
{
Redis *r = new Redis();
if (!r->connect("192.168.13.128", 6379))
{
printf("connect error!\n");
return 0;
}
r->set("name", "Mayuyu");
printf("Get the name is %s\n", r->get("name").c_str());
delete r;
return 0;
}
Makefile
redis: redis.cpp redis.h g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis clean: rm redis.o redis
注意 g++ 與 rm 之前都是一個 tab 字元,用空白會直接報錯。編譯指令為:
g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis
在 /etc/ld.so.conf.d/ 目錄下新增一個檔案 usr-libs.conf,內容寫入 /usr/local/lib,然後執行 /sbin/ldconfig 更新快取即可。
set 沒有釋放 redisCommand 回傳的 reply,長時間運行會累積記憶體;get 在 key 不存在時 reply->str 為 NULL,直接指派給 std::string 會崩潰。正式使用前建議補上 reply 判斷與 freeReplyObject,並在解構子中呼叫 redisFree。