相信做過服務端開發的應該都知道Redis的大名,它是一個開源的使用ANSI C語言編寫、支持網絡、可基於內存亦可持久化的日誌型、Key-Value數據庫,我們後臺是用C++開發的,問了下他們,用的緩存框架有Redis,SSDB,今天看了幾個帖子,簡單瞭解Redis的用法。記錄一下過程。
首先去官網下載最新的Redis源碼
http://redis.io/
解壓之後,進入目錄編譯
make
make test
sudo make install
下載hredis
https://github.com/redis/hiredis
解壓之後,同樣的
make
sudo make install
進入Redis的src目錄
啓動服務
./redis-server
redis-cli
連接成功...
代碼測試
新建一個臨時目錄
創建新文件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("127.0.0.1", 6379))
{
printf("connect error!\n");
return 0;
}
r->set("name", "Andy");
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
進行編譯
make
或者命令行執行
g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis
運行如果出現找不到動態鏈接庫
在/etc/ld.so.conf.d/目錄下新建文件usr-libs.conf,內容是:/usr/local/lib
最後執行
參考
http://blog.csdn.net/achelloworld/article/details/41598389?utm_source=tuicool&utm_medium=referral