redis数据库安装和C++调用
redis安装:
http://www.yiibai.com/redis/redis_environment.html
sudo apt-get update sudo apt-get install redis-server
redis相关:
https://www.cnblogs.com/idiotgroup/p/5455282.html
C++ 操作redis
首先安装hiredis依赖库:
git clone https://github.com/redis/hiredis cd hiredis make sudo make install(复制生成的库到/usr/local/lib目录下) sudo ldconfig /usr/local/lib
接下来新建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
最后执行:
http://blog.csdn.net/imxiangzi/article/details/52426086