PageRenderTime 264ms CodeModel.GetById 120ms app.highlight 7ms RepoModel.GetById 134ms app.codeStats 0ms

/hiredis/example.c

http://github.com/nicolasff/webdis
C | 73 lines | 54 code | 12 blank | 7 comment | 9 complexity | 85c269055ffbb1ddb17e7365576b8e7e MD5 | raw file
 1#include <stdio.h>
 2#include <stdlib.h>
 3#include <string.h>
 4
 5#include "hiredis.h"
 6
 7int main(void) {
 8    unsigned int j;
 9    redisContext *c;
10    redisReply *reply;
11
12    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
13    c = redisConnectWithTimeout((char*)"127.0.0.1", 6379, timeout);
14    if (c == NULL || c->err) {
15        if (c) {
16            printf("Connection error: %s\n", c->errstr);
17            redisFree(c);
18        } else {
19            printf("Connection error: can't allocate redis context\n");
20        }
21        exit(1);
22    }
23
24    /* PING server */
25    reply = redisCommand(c,"PING");
26    printf("PING: %s\n", reply->str);
27    freeReplyObject(reply);
28
29    /* Set a key */
30    reply = redisCommand(c,"SET %s %s", "foo", "hello world");
31    printf("SET: %s\n", reply->str);
32    freeReplyObject(reply);
33
34    /* Set a key using binary safe API */
35    reply = redisCommand(c,"SET %b %b", "bar", 3, "hello", 5);
36    printf("SET (binary API): %s\n", reply->str);
37    freeReplyObject(reply);
38
39    /* Try a GET and two INCR */
40    reply = redisCommand(c,"GET foo");
41    printf("GET foo: %s\n", reply->str);
42    freeReplyObject(reply);
43
44    reply = redisCommand(c,"INCR counter");
45    printf("INCR counter: %lld\n", reply->integer);
46    freeReplyObject(reply);
47    /* again ... */
48    reply = redisCommand(c,"INCR counter");
49    printf("INCR counter: %lld\n", reply->integer);
50    freeReplyObject(reply);
51
52    /* Create a list of numbers, from 0 to 9 */
53    reply = redisCommand(c,"DEL mylist");
54    freeReplyObject(reply);
55    for (j = 0; j < 10; j++) {
56        char buf[64];
57
58        snprintf(buf,64,"%d",j);
59        reply = redisCommand(c,"LPUSH mylist element-%s", buf);
60        freeReplyObject(reply);
61    }
62
63    /* Let's check what we have inside the list */
64    reply = redisCommand(c,"LRANGE mylist 0 -1");
65    if (reply->type == REDIS_REPLY_ARRAY) {
66        for (j = 0; j < reply->elements; j++) {
67            printf("%u) %s\n", j, reply->element[j]->str);
68        }
69    }
70    freeReplyObject(reply);
71
72    return 0;
73}