This article explores in connecting and using Redis with a C++ application. This tutorial is aimed at beginners, thus provides simple, easy-to-follow guide Redis usage.
Requirements
Since this tutorial is beginner friendly, first you must have a basic knowledge of working with Redis and C++.
Second, install a Redis server and C++ build tools on your system.
Installing Dependencies
To use Redis with C++, we need to install a C++ Redis client. For this tutorial, we will use redis-plus-plus client.
https://github.com/sewenew/redis-plus-plus
The first step is to update your system and install the required packages. The commands are as shown below:
$ sudo apt-get upgrade
Next, we need to install hiredis, a minimalistic C client for Redis.
Start by cloning the repository as:
Navigate into the directory and build the package from source:
$ make
Install the package as:
Once installed, we can proceed and install the Redis C++ client.
Start by cloning the repository as:
Navigate into the directory and run the following commands to build the package.
$ mkdir build
$ cd build
$ cmake -DREDIS_PLUS_PLUS_CXX_STANDARD=17 ..
Make and install.
$ sudo make install
Once completed, we can proceed.
Connecting C++ to Redis
The first step is to connect to our Redis server. Start by creating a working directory.
$ cd redis_cpp
Add the file to hold the source code for our application.
Open the file with your favorite text editor and add the code as shown:
# include <iostream>
using namespace sw::redis;
int main(void) {
auto redis = Redis("tcp://default:[email protected]:6379/0");
std::cout << redis.ping() << std::endl;
}
In the example above, we import the redis library to connect and perform tasks on the Redis server.
We create a redis object with the credentials to connect to the server in the main function.
If your server is not secured with a password, you can pass the URL as:
Next, compile the code to test if the connection to the server is established:
Run the program as:
If the connection is successful, the command above should return PONG:
Redis Set Key-Value Pair
To add a new key-value pair to the redis database, use the set function as shown:
Redis Get Value
You can also fetch the value associated with a specific key using the get method. An example code is as shown below:
if (value) {
// Dereference val to get the returned value
std::cout << *value << std::endl;
}
Once you compile and run the code above, you should get an output as shown:
Conclusion
After you have followed through all the guidelines and examples provided, you should be able to connect and use Redis with C++. This is the most basic guide that allows beginners to avoid complex Redis usage. Explore the documentation to learn more.