C/C++连接腾讯云数据库Redis

C/C++连接

下面是一个c/c++连接Jmiss-Redis的示例:

  • step1:下载安装c/c++连接redis的c客户端

gitclonehttps://github.com/redis/hiredis.gitcdhiredismakesudomakeinstallldconfig

  • step2:编写测试代码

#includestdio.h#includestdlib.h#includestring.h#includehiredis.hintmain(intargc,charargv){unsignedintj;redisContextc;redisReplyreply;if(argc3){printf("Usage:examplejredis-cn-north-1-prod-redis-xxxxxxxxxx.jdcloud.com6379password ");exit(0);}constcharhostname=argv[1];constintport=atoi(argv[2]);constcharpassword=argv[3];structtimevaltimeout={1,500000};//1.5secondsc=redisConnectWithTimeout(hostname,port,timeout);if(c==NULL||c-err){if(c){printf("Connectionerror:%s ",c-errstr);redisFree(c);}else{printf("Connectionerror:can'tallocaterediscontext ");}exit(1);}/AUTH/reply=redisCommand(c,"AUTH%s",password);printf("AUTH:%s ",reply-str);freeReplyObject(reply);/PINGserver/reply=redisCommand(c,"PING");printf("PING:%s ",reply-str);freeReplyObject(reply);/Setakey/reply=redisCommand(c,"SET%s%s","foo","helloworld");printf("SET:%s ",reply-str);freeReplyObject(reply);/SetakeyusingbinarysafeAPI/reply=redisCommand(c,"SET%b%b","bar",(size_t)3,"hello",(size_t)5);printf("SET(binaryAPI):%s ",reply-str);freeReplyObject(reply);/TryaGETandtwoINCR/reply=redisCommand(c,"GETfoo");printf("GETfoo:%s ",reply-str);freeReplyObject(reply);reply=redisCommand(c,"INCRcounter");printf("INCRcounter:%lld ",reply-integer);freeReplyObject(reply);/again.../reply=redisCommand(c,"INCRcounter");printf("INCRcounter:%lld ",reply-integer);freeReplyObject(reply);/Createalistofnumbers,from0to9/reply=redisCommand(c,"DELmylist");freeReplyObject(reply);for(j=0;j10;j++){charbuf[64];snprintf(buf,64,"%d",j);reply=redisCommand(c,"LPUSHmylistelement-%s",buf);freeReplyObject(reply);}/Let'scheckwhatwehaveinsidethelist/reply=redisCommand(c,"LRANGEmylist0-1");if(reply-type==REDIS_REPLY_ARRAY){for(j=0;jreply-elements;j++){printf("%u)%s ",j,reply-element[j]-str);}}freeReplyObject(reply);/Disconnectsandfreesthecontext/redisFree(c);return0;}

step3:编译

gcc-oexample-gexample.c-I/usr/local/include/hiredis–lhiredis

step4:运行测试用例

./examplejredis-cn-north-1-prod-redis-xxxxxxxxxx.jdcloud.com6379passwordAUTH:OKPING:PONGSET:OKSET(binaryAPI):OKGETfoo:helloworldINCRcounter:3INCRcounter:40)element-91)element-82)element-73)element-64)element-55)element-46)element-37)element-28)element-19)element-0