HomeDocsDevelopC

Documentation

C and Redis

Ajeet Raina
Author
Ajeet Raina, Former Developer Growth Manager at Redis

Find tutorials, examples and technical articles that will help you to develop with Redis and C.

Getting started#

In order to use Redis with C, you need a C Redis client. For your first steps with C and Redis, this article will show how to use the recommended library: hiredis.

Step 1. Install the pre-requisites#

Version 1.0.0 marks the first stable release of Hiredis. Follow the below steps to install the pre-requisite packages in order to compile the latest version of hiredis.

 brew install gcc make

Run the below command to run Redis server

 redis-server

Step 2. Install and compile hiredis#

wget https://github.com/redis/hiredis/archive/master.zip
 make
 make install

Step 3. Copy the below C code:#

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <hiredis/hiredis.h>

 int main (int argc, char **argv) {
   redisReply *reply;
   redisContext *c;

   c = redisConnect("127.0.0.1", 6381);
   if (c->err) {
       printf("error: %s\n", c->errstr);
       return 1;
   }

   /* PINGs */
   reply = redisCommand(c,"PING %s", "Hello World");
   printf("RESPONSE: %s\n", reply->str);
   freeReplyObject(reply);

   redisFree(c);
 }

Step 4. Compile the code#

 gcc redistest.c -o redistest -I /usr/local/include/hiredis -lhiredis

Step 5. Test the code#

 ./redistest
 RESPONSE: Hello World

More C Clients Resources#

  • hiredis-cluster - C client library for Redis Cluster
  • libredis - A C based general low-level PHP extension and client library for Redis, focusing on performance, generality and efficient parallel communication with multiple Redis servers.
  • hiredispool - Provides connection pooling and auto-reconnect for hiredis. It is also minimalistic and easy to do customization.