Redis --> Redis的接口介紹及使用


Redis的接口介紹及使用

  Redis是一個遠程內存數據庫,它不僅性能強勁,而且還具有復制特性以及為解決問題而生的獨一無二的數據模型。Redis提供了5種不同類型的數據結構,各式各樣的問題都可以很自然地映射到這些數據結構上:Redis的數據結構致力於幫助用戶解決問題,而不會像其他數據庫那樣,要求用戶扭曲問題來適應數據庫。除此之外,通過復制、持久化(persistence)和客戶端分片(client-side sharding)等特性,用戶可以很方便地將Redis擴展成一個能夠包含數百GB數據、每秒處理上百萬次請求的系統。

 

一、接口說明

1) 連接數據庫

redisContext* redisConnect(const char *ip, int port)
redisContext* redisConnectWithTimeout(const char *ip, int port, timeval tv)

該函數用來連接redis數據庫, 兩個參數分別是redis數據庫的ip和端口,端口號一般為6379。類似的還提供了一個函數,供連接超時限定。

2)執行命令

void *redisCommand(redisContext *c, const char *format...)

該函數用於執行redis數據庫中的命令,第一個參數為連接數據庫返回的redisContext,剩下的參數為變參,如同C語言中的prinf()函數。此函數的返回值為void*,但是一般會強制轉換為redisReply類型,以便做進一步的處理。

3)釋放內存

void freeReplyObject(void *reply)

釋放redisCommand執行后返回的的redisReply所占用的內存。

4)斷開連接

void redisFree(redisContext *c)

釋放redisConnect()所產生的連接。

 

二、Redis的使用

1、網站下載hiredis.tar.gz包

2、然后執行make進行編譯

3、把libhiredis.so放到/usr/local/lib/中,把hiredis.h放到/usr/local/inlcude/hiredis/中;或者直接用命令make install配置。

4、在程序中包含#include <hiredis/hiredis.h>即可。

 

示例一:

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_

主函數

#include "redis.h"

int main()
{
   Redis *r = new Redis();
   if(!r->connect("192.168.13.128", 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;
}

makefile文件

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

clean:
  rm redis.o redis

在執行的時候如果出現動態庫無法加載:

  1)在 /etc/ld.so.conf.d/ 目錄下新建文件 usr-libs.conf ,添加 /usr/local/lib ;

  2)使用命令 /sbin/ldconfig 更新一下配置即可。

 

示例二:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <hiredis.h>

void doTest()
{
    int timeout = 10000;
    struct timeval tv;
    tv.tv_sec = timeout / 1000;
    tv.tv_usec = timeout * 1000;
    //以帶有超時的方式鏈接Redis服務器,同時獲取與Redis連接的上下文對象。
    //該對象將用於其后所有與Redis操作的函數。
    redisContext* c = redisConnectWithTimeout("192.168.149.137",6379,tv);
    if (c->err) {
        redisFree(c);
        return;
    }
    const char* command1 = "set stest1 value1";
    redisReply* r = (redisReply*)redisCommand(c,command1);
    //需要注意的是,如果返回的對象是NULL,則表示客戶端和服務器之間出現嚴重錯誤,必須重新鏈接。
    //這里只是舉例說明,簡便起見,后面的命令就不再做這樣的判斷了。
    if (NULL == r) {
        redisFree(c);
        return;
    }
    //不同的Redis命令返回的數據類型不同,在獲取之前需要先判斷它的實際類型。
    //至於各種命令的返回值信息,可以參考Redis的官方文檔,或者查看該系列博客的前幾篇
    //有關Redis各種數據類型的博客。:)
    //字符串類型的set命令的返回值的類型是REDIS_REPLY_STATUS,然后只有當返回信息是"OK"
    //時,才表示該命令執行成功。后面的例子以此類推,就不再過多贅述了。
    if (!(r->type == REDIS_REPLY_STATUS && strcasecmp(r->str,"OK") == 0)) {
        printf("Failed to execute command[%s].\n",command1);
        freeReplyObject(r);
        redisFree(c);
        return;
    }
    //由於后面重復使用該變量,所以需要提前釋放,否則內存泄漏。
    freeReplyObject(r);
    printf("Succeed to execute command[%s].\n",command1);

    const char* command2 = "strlen stest1";
    r = (redisReply*)redisCommand(c,command2);
    if (r->type != REDIS_REPLY_INTEGER) {
        printf("Failed to execute command[%s].\n",command2);
        freeReplyObject(r);
        redisFree(c);
        return;
    }
    int length = r->integer;
    freeReplyObject(r);
    printf("The length of 'stest1' is %d.\n",length);
    printf("Succeed to execute command[%s].\n",command2);

    const char* command3 = "get stest1";
    r = (redisReply*)redisCommand(c,command3);
    if (r->type != REDIS_REPLY_STRING) {
        printf("Failed to execute command[%s].\n",command3);
        freeReplyObject(r);
        redisFree(c);
        return;
    }
    printf("The value of 'stest1' is %s.\n",r->str);
    freeReplyObject(r);
    printf("Succeed to execute command[%s].\n",command3);

    const char* command4 = "get stest2";
    r = (redisReply*)redisCommand(c,command4);
    //這里需要先說明一下,由於stest2鍵並不存在,因此Redis會返回空結果,這里只是為了演示。
    if (r->type != REDIS_REPLY_NIL) {
        printf("Failed to execute command[%s].\n",command4);
        freeReplyObject(r);
        redisFree(c);
        return;
    }
    freeReplyObject(r);
    printf("Succeed to execute command[%s].\n",command4);

    const char* command5 = "mget stest1 stest2";
    r = (redisReply*)redisCommand(c,command5);
    //不論stest2存在與否,Redis都會給出結果,只是第二個值為nil。
    //由於有多個值返回,因為返回應答的類型是數組類型。
    if (r->type != REDIS_REPLY_ARRAY) {
        printf("Failed to execute command[%s].\n",command5);
        freeReplyObject(r);
        redisFree(c);
        //r->elements表示子元素的數量,不管請求的key是否存在,該值都等於請求是鍵的數量。
        assert(2 == r->elements);
        return;
    }
    for (int i = 0; i < r->elements; ++i) {
        redisReply* childReply = r->element[i];
        //之前已經介紹過,get命令返回的數據類型是string。
        //對於不存在key的返回值,其類型為REDIS_REPLY_NIL。
        if (childReply->type == REDIS_REPLY_STRING)
            printf("The value is %s.\n",childReply->str);
    }
    //對於每一個子應答,無需使用者單獨釋放,只需釋放最外部的redisReply即可。
    freeReplyObject(r);
    printf("Succeed to execute command[%s].\n",command5);

    printf("Begin to test pipeline.\n");
    //該命令只是將待發送的命令寫入到上下文對象的輸出緩沖區中,直到調用后面的
    //redisGetReply命令才會批量將緩沖區中的命令寫出到Redis服務器。這樣可以
    //有效的減少客戶端與服務器之間的同步等候時間,以及網絡IO引起的延遲。
    //至於管線的具體性能優勢,可以考慮該系列博客中的管線主題。
    if (REDIS_OK != redisAppendCommand(c,command1)
        || REDIS_OK != redisAppendCommand(c,command2)
        || REDIS_OK != redisAppendCommand(c,command3)
        || REDIS_OK != redisAppendCommand(c,command4)
        || REDIS_OK != redisAppendCommand(c,command5)) {
        redisFree(c);
        return;
    }

    redisReply* reply = NULL;
    //對pipeline返回結果的處理方式,和前面代碼的處理方式完全一直,這里就不再重復給出了。
    if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
        printf("Failed to execute command[%s] with Pipeline.\n",command1);
        freeReplyObject(reply);
        redisFree(c);
    }
    freeReplyObject(reply);
    printf("Succeed to execute command[%s] with Pipeline.\n",command1);

    if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
        printf("Failed to execute command[%s] with Pipeline.\n",command2);
        freeReplyObject(reply);
        redisFree(c);
    }
    freeReplyObject(reply);
    printf("Succeed to execute command[%s] with Pipeline.\n",command2);

    if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
        printf("Failed to execute command[%s] with Pipeline.\n",command3);
        freeReplyObject(reply);
        redisFree(c);
    }
    freeReplyObject(reply);
    printf("Succeed to execute command[%s] with Pipeline.\n",command3);

    if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
        printf("Failed to execute command[%s] with Pipeline.\n",command4);
        freeReplyObject(reply);
        redisFree(c);
    }
    freeReplyObject(reply);
    printf("Succeed to execute command[%s] with Pipeline.\n",command4);

    if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
        printf("Failed to execute command[%s] with Pipeline.\n",command5);
        freeReplyObject(reply);
        redisFree(c);
    }
    freeReplyObject(reply);
    printf("Succeed to execute command[%s] with Pipeline.\n",command5);
    //由於所有通過pipeline提交的命令結果均已為返回,如果此時繼續調用redisGetReply,
    //將會導致該函數阻塞並掛起當前線程,直到有新的通過管線提交的命令結果返回。
    //最后不要忘記在退出前釋放當前連接的上下文對象。
    redisFree(c);
    return;
}

int main() 
{
    doTest();
    return 0;
}

//輸出結果如下:
//Succeed to execute command[set stest1 value1].
//The length of 'stest1' is 6.
//Succeed to execute command[strlen stest1].
//The value of 'stest1' is value1.
//Succeed to execute command[get stest1].
//Succeed to execute command[get stest2].
//The value is value1.
//Succeed to execute command[mget stest1 stest2].
//Begin to test pipeline.
//Succeed to execute command[set stest1 value1] with Pipeline.
//Succeed to execute command[strlen stest1] with Pipeline.
//Succeed to execute command[get stest1] with Pipeline.
//Succeed to execute command[get stest2] with Pipeline.
//Succeed to execute command[mget stest1 stest2] with Pipeline.

 

參考:

http://blog.csdn.net/achelloworld/article/details/41598389

http://www.cnblogs.com/stephen-liu74/archive/2012/04/13/2398249.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM