Hiredis是redis開源庫對C語言介面的API開發庫。
1. 初學者很容易搞混,redis-server redis-client都是應用程式,跟開發介面不相關。
http://redis.io/download 中介紹的
Installation
Download, extract and compile Redis with:
$ wget http://download.redis.io/releases/redis-2.8.3.tar.gz
$ tar xzf redis-2.8.3.tar.gz
$ cd redis-2.8.3
$ make
The binaries that are now compiled are available in the src directory. Run Redis with:
$ src/redis-server
You can interact with Redis using the built-in client:
$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"
也是服務端和用戶端的安裝與使用。
2. Hiredis 在官網 http://redis.io/clients 中有說明This is the official C client. Support for the whole command set, pipelining, event driven programming.
下載地址為: https://github.com/redis/hiredis
3. 在Linux平台下載hiredis開發包,解壓
在命令列中 cd進入解壓後的檔案夾執行 Make 這樣C用戶端編譯完畢。
接下來也是最關鍵的 配置。
可以手動設定 將對應.h與.so .a等檔案拷貝到/usr/local/lib /user/local/include對應檔案夾
或者直接執行自動設定 make install 建議直接使用此方法。
至此hiredis開發包配置完畢
4. 編寫程式
可以編寫依賴hiredis 的程式了,
標頭檔需要包含 include <hiredis/hiredis.h>,然後編譯的時候加上 -lhiredis
如果使用eclipse cdt 是在下圖中對應加入連結庫
或者自己編寫的makefile檔案中加入 LDFLAGS = -lhiredis
-lhiredis 連結選項 這個設定當初讓我很迷惑,
它其實解析出全程就是libhiredis.so,就是程式運行時載入libhiredis.so redis的動態庫
同理-lpthread 也就是libpthread.so
至此下述代碼編譯通過
#include <iostream>
using namespace std;
#include <hiredis/hiredis>
int main()
{
cout<<"Hello World!!"<<endl;
redisContext *conn = NULL;
*conn = redisConnect("127.0.0.1", 6379); //redis server預設連接埠
if(conn->err)
{
printf("connection error: %s", conn->str);
}
}
5. 如果編譯通過但是運行時候提示提示動態庫載入失敗
error while loading shared libraries XXXXX