Redis之二

hiredis下载地址:https://codeload.github.com/redis/hiredis/zip/master

二.redis C++接口
来源:http://blog.csdn.net/muyuxuebao/article/details/51038179


1.安装hiredis

# wget https://codeload.github.com/redis/hiredis/zip/master
# tar xzvf master  #有可能不行,那就用# unzip master
# cd hiredis-master
# make
# sudo make install

2.观察make install时libhiredis.so.0.13被放到了哪个文件夹里,比如/usr/local/lib,然后执行以下命令

# sudo ldconfig /usr/local/lib/
#此命令用于程序启动时查找库

注:ldconfig提示is not a symbolic link警告的去除方法 
    来源:http://blog.chinaunix.net/uid-20564848-id-74664.html
    错误提示:
    ldconfig 
    ldconfig: /usr/local/lib/gliethttp/libxerces-c-3.0.so is not a symbolic link
    问题分析:
    因为libxerces-c-3.0.so正常情况下应该是一个符号链接,而不是实体文集件,修改其为符号链接即可
    解决方法:
    # mv libxerces-c-3.0.so libxerces-c.so.3.0
    # ln -s libxerces-c.so.3.0 libxerces-c-3.0.so
    这样就ok了

3.开启redis

# /etc/init.d/redis start

4.测试代码

redis.h
/*
 * redis.h
 *  Created on: Apr 1, 2016
 *  Author: liang
 */

#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("localhost", 6379)) {
        printf("connect error!\n");
        return 0;
    }
    r->set("name", "Mayuyu");
    printf("Get the name is %s\n", r->get("name").c_str());
    delete r;
    return 0;
}
//命令行执行
# g++ redis.cpp -lhiredis -o redis
# ./redis

猜你喜欢

转载自blog.csdn.net/weixu1999/article/details/81042964
今日推荐