c/c++使用redis
生活随笔
收集整理的這篇文章主要介紹了
c/c++使用redis
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
c/c++使用redis
- hiredis
- 1、安裝hiredis
- 2、接口介紹
- c程序操作Redis代碼
hiredis
hiredis是Redis官方推薦的基于C接口的客戶端組件,它提供接口,供c語(yǔ)言調(diào)用以操作數(shù)據(jù)庫(kù)。
1、安裝hiredis
進(jìn)入Redis的源碼包的deps/hiredis
make
make install
ldconfig #使動(dòng)態(tài)庫(kù)在系統(tǒng)中更新生效
2、接口介紹
#include <hiredis/hiredis.h>// 該函數(shù)用來(lái)連接redis數(shù)據(jù)庫(kù),參數(shù)為ip地址和端口號(hào),默認(rèn)端口6379.該函數(shù)返回一個(gè)redisContext對(duì)象 redisContext *redisConnect(const char *ip, int port);// 該函數(shù)執(zhí)行redis命令,返回redisReply對(duì)象 void *redisCommand(redisContext *c, const char *format, ...);// 釋放redisCommand執(zhí)行后返回的RedisReply對(duì)象 void freeReplyObject(void *reply);// 斷開(kāi)redisConnect所產(chǎn)生的連接 void redisFree(redisContext *c);//redisReply對(duì)象結(jié)構(gòu)如下: typedef struct redisReply {int type; // 返回結(jié)果類型long long integer; // 返回類型為整型的時(shí)候的返回值size_t len; // 字符串的長(zhǎng)度char *str; // 返回錯(cuò)誤類型或者字符串類型的字符串size_t elements; // 返回?cái)?shù)組類型時(shí),元素的數(shù)量struct redisReply **element; // 元素結(jié)果集合 }redisReply;// 返回類型有一下幾種: REDIS_REPLY_STRING 1 //字符串 REDIS_REPLY_ARRAY 2 //數(shù)組,多個(gè)reply,通過(guò)element數(shù)組以及elements數(shù)組大小訪問(wèn) REDIS_REPLY_INTEGER 3 //整型 REDIS_REPLY_NIL 4 //空,沒(méi)有數(shù)據(jù) REDIS_REPLY_STATUS 5 //狀態(tài),str字符串以及l(fā)en REDIS_REPLY_ERROR 6 //錯(cuò)誤,同STATUSc程序操作Redis代碼
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <hiredis/hiredis.h>int main() {redisContext * rc = redisConnect("127.0.0.1",6379);assert(rc != NULL);char* com = "hmset user name jack age 18 sex male height 180";redisReply* res =(redisReply*)redisCommand(rc,com);if(res->type == REDIS_REPLY_STATUS){printf("Success %s\n",res->str);}else printf("fail\n");com = "hgetall user";res = (redisReply*)redisCommand(rc,com);if(res->type == REDIS_REPLY_ARRAY){for(int i = 0; i < res->elements; i++){if(i%2 != 0)printf("%s\n",res->element[i]->str);elseprintf("%s",res->element[i]->str);}}else if(res->type == REDIS_REPLY_STRING){printf("%s",res->str);}freeReplyObject(res);redisFree(rc);return 1; }總結(jié)
以上是生活随笔為你收集整理的c/c++使用redis的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 分析静态网页客户服务器工作过程,(静态网
- 下一篇: C++十进制转换为二进制