Skip to content

Instantly share code, notes, and snippets.

@alvarow
Last active July 7, 2016 21:56
Show Gist options
  • Save alvarow/66b373145a8fd08fe7d8b967e03c5556 to your computer and use it in GitHub Desktop.
Save alvarow/66b373145a8fd08fe7d8b967e03c5556 to your computer and use it in GitHub Desktop.
Redist PING, SET, GET example. Requires hiredis library
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hiredis.h"
// Shameless copy of example.c
// Depends on hiredis - download and make, drop this file on the hiredis folder and run
// gcc alvaro-redis.c libhiredis.a -o alvaro-redis -static
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", "alvaro", "was here");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Try a GET */
reply = redisCommand(c,"GET alvaro");
printf("GET alvaro: %s\n", reply->str);
freeReplyObject(reply);
/* DEL alvaro */
reply = redisCommand(c,"DEL alvaro");
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment