相信做过服务端开发的应该都知道Redis的大名,它是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,我们后台是用C++开发的,问了下他们,用的缓存框架有Redis,SSDB,今天看了几个帖子,简单了解Redis的用法。记录一下过程。
首先去官网下载最新的Redis源码http://redis.io/解压之后,进入目录编译
makemake testsudo make install下载hredishttps://github.com/redis/hiredis解压之后,同样的
makesudo make install进入Redis的src目录启动服务
#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/ -lhiredisclean: rm redis.o redis进行编译
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
FROM:http://www.jianshu.com/p/11f4c7c71953新闻热点
疑难解答
图片精选