hiredis/examples/example.c

92 lines
2.6 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
#include <win32.h>
int main(int argc, char **argv) {
unsigned int j, isunix = 0;
2010-09-24 16:48:07 +00:00
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
if (argc > 2) {
if (*argv[2] == 'u' || *argv[2] == 'U') {
isunix = 1;
/* in this case, host is the path to the unix socket */
printf("Will connect to unix socket @%s\n", hostname);
}
}
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
if (isunix) {
c = redisConnectUnixWithTimeout(hostname, timeout);
} else {
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 */
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key */
2010-09-24 16:48:07 +00:00
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);
2010-05-18 16:13:25 +00:00
/* Try a GET and two INCR */
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"GET foo");
printf("GET foo: %s\n", reply->str);
2010-05-18 16:13:25 +00:00
freeReplyObject(reply);
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"INCR counter");
2010-05-18 16:13:25 +00:00
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* again ... */
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"INCR counter");
2010-05-18 16:13:25 +00:00
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
2010-05-18 15:45:36 +00:00
/* Create a list of numbers, from 0 to 9 */
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"DEL mylist");
2010-05-18 16:13:25 +00:00
freeReplyObject(reply);
2010-05-18 15:45:36 +00:00
for (j = 0; j < 10; j++) {
char buf[64];
2015-10-05 13:22:00 +00:00
snprintf(buf,64,"%u",j);
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
2010-05-18 15:45:36 +00:00
freeReplyObject(reply);
}
/* Let's check what we have inside the list */
2010-09-24 16:48:07 +00:00
reply = redisCommand(c,"LRANGE mylist 0 -1");
2010-05-18 15:45:36 +00:00
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
2010-05-18 15:45:36 +00:00
}
}
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}