博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
最简单的使用redis自带程序实现c程序远程访问redis服务
阅读量:4066 次
发布时间:2019-05-25

本文共 2318 字,大约阅读时间需要 7 分钟。

代码在下面,包含主要头文件 hiredis.h 用来定义与服务端的连接

函数 redisConnectWithTimeout 用来连接,有超时设置;

函数 redisCommand 用来执行命令

函数 freeReplyObject 和函数redisFree 用来释放 之前的资源。

整体代码比较简单,主要是执行命令。

#include 
#include
#include
#include
int main(int argc, char **argv) { unsigned int j; redisContext *c; redisReply *reply; const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1"; int port = (argc > 2) ? atoi(argv[2]) : 6379; struct timeval timeout = { 1, 500000 }; // 1.5 seconds c = redisConnectWithTimeout(hostname, port, timeout); if (c == NULL || c->err) { if (c) { printf("Connection error: %s\n", c->errstr); redisFree(c); } else { printf("Connection error: can't allocate redis context\n"); } exit(1); } /* PING server */ reply = redisCommand(c,"PING"); printf("PING: %s\n", reply->str); freeReplyObject(reply); /* Set a key */ reply = redisCommand(c,"SET %s %s", "foo", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* Set a key using binary safe API */ reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); printf("SET (binary API): %s\n", reply->str); freeReplyObject(reply); /* Try a GET and two INCR */ reply = redisCommand(c,"GET foo"); printf("GET foo: %s\n", reply->str); freeReplyObject(reply); reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* again ... */ reply = redisCommand(c,"INCR counter"); printf("INCR counter: %lld\n", reply->integer); freeReplyObject(reply); /* Create a list of numbers, from 0 to 9 */ reply = redisCommand(c,"DEL mylist"); freeReplyObject(reply); for (j = 0; j < 10; j++) { char buf[64]; snprintf(buf,64,"%u",j); reply = redisCommand(c,"LPUSH mylist element-%s", buf); freeReplyObject(reply); } /* Let's check what we have inside the list */ reply = redisCommand(c,"LRANGE mylist 0 -1"); if (reply->type == REDIS_REPLY_ARRAY) { for (j = 0; j < reply->elements; j++) { printf("%u) %s\n", j, reply->element[j]->str); } } freeReplyObject(reply); /* Disconnects and frees the context */ redisFree(c); return 0;}

 

转载地址:http://zktji.baihongyu.com/

你可能感兴趣的文章
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
web test flow
查看>>
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>
OS + UNIX AIX command
查看>>
OS + UNIX AIX performance
查看>>
OS + UNIX AIX Tools
查看>>
my ReadBook_liutongjingjixue / circulation economics
查看>>
my ReadBook_wangluoyingxiaoyucehua / network marketing / wangluoyingxiao
查看>>
db base database
查看>>
不联网的情况下,CentOs下载成功卸载 virbr0
查看>>
SAE 搭建 Discuz
查看>>
天地水火雷风山泽 乾坤坎离震巽艮兑
查看>>
数据流图的画法(转)
查看>>
eclips指定使用哪个jdk
查看>>
使用 AppFuse 的七个理由学习
查看>>
使用 AppFuse 快速构建 J2EE 应用
查看>>
AppFuse 2.0初体验
查看>>
拍美女看这里人像摄影终极POSE指南
查看>>
maven快速搭建
查看>>