Redis的C語言客戶端(hiredis)的安裝和使用


關鍵詞:hirediscRedisredis clientsredis客戶端C客戶端華為雲分布式緩存服務

hiredis是一個非常全面的C語言版redis接口庫,支持所有命令、管道與腳本。華為雲分布式緩存服務Redis版支持hiredis客戶端連接。

使用C語言客戶端(hiredis)連接Redis,需要先安裝編譯環境以及hiredis,以CentOS為例,介紹C客戶端環境搭建。

第0步:准備工作

華為雲上購買1台彈性雲服務器ECS(我選了CentOS 6.3),一個分布式緩存實例(DCS for Redis),我選了個單機實例。

注意ECS和緩存實例配置相同的VPC和安全組,確保網絡互通。

第1步:安裝gcc、make和hiredis

如果系統沒有自帶編譯環境,可以使用yum方式安裝。

yum install gcc make

下載並解壓hiredis

wget https://github.com/redis/hiredis/archive/master.zip;

進入到解壓目錄后編譯安裝

make 

make install

安裝完成后即可嘗試連接。

第2步:連接Redis

關於hiredis的使用,redis官網給了詳細的使用介紹。這里舉一個簡單的例子,介紹連接、密碼鑒權、set以及get方法。

編輯連接demo實例,如:

vim connRedis.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
     unsigned int j;
     redisContext *conn;
     redisReply *reply;
     if (argc < 3) {
             printf("Usage: example {instance_ip_address} 6379 {password}\n");
             exit(0);
     }
     const char *hostname = argv[1];
     const int port = atoi(argv[2]);
     const char *password = argv[3];
     struct timeval timeout = { 1, 500000 }; // 1.5 seconds
     conn = redisConnectWithTimeout(hostname, port, timeout);
     if (conn == NULL || conn->err) {
		if (conn) {
             printf("Connection error: %s\n", conn->errstr);
             redisFree(conn);
		} else {
             printf("Connection error: can't allocate redis context\n");
		}
     exit(1);
     }
     /* AUTH */
     reply = redisCommand(conn, "AUTH %s", password);
     printf("AUTH: %s\n", reply->str);
     freeReplyObject(reply);

     /* Set */
     reply = redisCommand(conn,"SET %s %s", "welcome", "Hello, DCS for Redis!");
     printf("SET: %s\n", reply->str);
     freeReplyObject(reply);
    
     /* Get */
     reply = redisCommand(conn,"GET welcome");
     printf("GET welcome: %s\n", reply->str);
     freeReplyObject(reply);
     
     /* Disconnects and frees the context */
     redisFree(conn);
     return 0;
}

保存后退出,執行以下命令編譯:

gcc connRedis.c -o connRedis  -I /usr/local/include/hiredis -lhiredis

如果有報錯,可查找hiredis.h文件路徑,並修改編譯命令。

編譯完后得到一個可執行文件connRedis,

測試以下命令測試連接:

 ./connRedis {redis_ip_address} 6379 {password}

得到以下回顯,則demo正常運行:

[root@ecs-herucentos heru]#  ./connRedis 192.168.0.171 6379 Heru+123
AUTH: OK
SET: OK
GET welcome: Hello, DCS for Redis!
[root@ecs-herucentos heru]# 

 

注意,如果運行報錯找不到hiredis庫文件,可參考如下,將相關文件拷貝到系統目錄,並增加動態鏈接。

mkdir /usr/lib/hiredis
cp /usr/local/lib/libhiredis.so.0.13 /usr/lib/hiredis/
mkdir /usr/include/hiredis
cp /usr/local/include/hiredis/hiredis.h /usr/include/hiredis/
echo '/usr/local/lib' >>/etc/ld.so.conf
ldconfig

以上so文件與.h文件的位置,需要替換成實際文件位置。

 


免責聲明!

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



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