Tutorial
C and Redis
February 26, 20262 minute read
TL;DR:Install hiredis, the recommended C Redis client library, compile it withmake, then useredisConnectandredisCommandto talk to your Redis server from any C program.
#What you'll learn
- How to install and compile the hiredis C client library
- How to connect to a Redis server from C
- How to execute Redis commands and handle replies
- Where to go next with async hiredis and Redis Cluster
#Prerequisites
- A C compiler (
gccorclang) makeandwget- Package manager:
brew(macOS) orapt(Linux) - A running Redis server
#How do I install hiredis?
Version 1.0.0 marks the first stable release of hiredis. Install the build tools you need, then download and compile hiredis from source.
Install the build prerequisites:
Start a Redis server if you don't already have one running:
Download and compile hiredis:
#How do I connect to Redis from a C program?
Create a file called
redistest.c with the following code. It opens a connection with redisConnect, sends a PING command, prints the reply, and cleans up.#How do I compile and run my C Redis program?
Compile the code with
gcc, linking against hiredis:Run the program:
#What about async connections?
hiredis also provides an asynchronous API for non-blocking I/O. The async interface integrates with event loops such as
libevent, libev, and libuv, making it suitable for high-throughput or embedded C applications that need to handle many concurrent Redis operations. See the hiredis async documentation for details.#Next steps
- Explore hiredis on GitHub for the full API reference
- Try hiredis-cluster, a C client library for Redis Cluster
- Check out hiredispool for connection pooling and auto-reconnect
- Browse the Redis command reference to see all available commands
