c++ operation redis

I believe that anyone who has done server-side development should know the name of Redis. It is an open source log-type and key-value database written in ANSI C language, supporting network, memory-based and persistent. Our background is developed in C++ Yes, I asked them. The caching frameworks used are Redis and SSDB. I read a few posts today and have a simple understanding of the usage of Redis. Document the process.

First go to the official website to download the latest Redis source code
http://redis.io/
After decompression, enter the directory to compile

make
make test
sudo make install

After downloading hredis
https://github.com/redis/hiredis
and decompressing, the same

make
sudo make install

Enter the src directory of Redis and
start the service

./redis-server
redis-cli


connection succeeded...

code test

Create a new temporary directory
Create a new file 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_

Create 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;
}

Write Makefiles

redis: redis.cpp redis.h
    g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis

clean:
    rm redis.o redis

to compile

make

or command line execution

g++ redis.cpp -o redis -L/usr/local/lib/ -lhiredis

Run if the dynamic link library cannot be found

在/etc/ld.so.conf.d/目录下新建文件usr-libs.conf,内容是:/usr/local/lib

final execution

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326686270&siteId=291194637