summaryrefslogtreecommitdiff
path: root/examples/example.c
diff options
context:
space:
mode:
authorAaron Bedra <aaron@aaronbedra.com>2013-04-19 15:39:26 -0500
committerPieter Noordhuis <pcnoordhuis@gmail.com>2013-07-10 22:16:53 -0700
commitc552ca6904f55c5eee40e309e31cf2d4325a84b6 (patch)
tree3a08471079c9976c63603e802b4c436fc7c1924c /examples/example.c
parent49de2cf99056bb5c33502ab86d9c397998d379ed (diff)
Move examples into their own folder
Closes #166.
Diffstat (limited to 'examples/example.c')
-rw-r--r--examples/example.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/examples/example.c b/examples/example.c
new file mode 100644
index 0000000..c135fd0
--- /dev/null
+++ b/examples/example.c
@@ -0,0 +1,73 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <hiredis.h>
+
+int main(void) {
+ unsigned int j;
+ redisContext *c;
+ redisReply *reply;
+
+ struct timeval timeout = { 1, 500000 }; // 1.5 seconds
+ c = redisConnectWithTimeout((char*)"127.0.0.1", 6379, 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", 3, "hello", 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,"%d",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);
+
+ return 0;
+}