C++操作Redis的简单例子

来源:互联网 发布:淘宝客服不在分流组 编辑:程序博客网 时间:2024/06/05 08:51

相信做过服务端开发的应该都知道Redis的大名,它是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,我们后台是用C++开发的,问了下他们,用的缓存框架有Redis,SSDB,今天看了几个帖子,简单了解Redis的用法。记录一下过程。

首先去官网下载最新的Redis源码
http://redis.io/
解压之后,进入目录编译

makemake testsudo make install

下载hredis
https://github.com/redis/hiredis
解压之后,同样的

makesudo 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/ -lhiredisclean:    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




FROM:http://www.jianshu.com/p/11f4c7c71953
0 0
原创粉丝点击