Working with Numbers in Redis Using C++

Working with Numbers in Redis Using C++

Welcome back to our Redis course! Now that you know how to connect to a Redis server, it's time to move forward and explore how to work with numbers in Redis. This unit builds on our previous lesson, so ensure you're comfortable with establishing a connection to a Redis server.

What You'll Learn

In this lesson, you will learn how to:

  1. Set numeric values in Redis.
  2. Retrieve and print numeric values.

Here's the code snippet that we'll be working with:

#include <iostream>
#include <hiredis/hiredis.h>

int main() {
    // Connect to Redis
    redisContext* context = redisConnect("127.0.0.1", 6379);
    if (context == NULL || context->err) {
        if (context) {
            std::cerr << "Error: " << context->errstr << std::endl;
            // handle error
        } else {
            std::cerr << "Can't allocate redis context" << std::endl;
        }
        return 1;
    }
    
    // Setting numeric values
    redisReply* reply;
    reply = (redisReply*)redisCommand(context, "SET count %d", 5);
    freeReplyObject(reply);
    reply = (redisReply*)redisCommand(context, "SET completion_rate %f", 95.5);
    freeReplyObject(reply);
    
    // Getting numeric values
    reply = (redisReply*)redisCommand(context, "GET count");
    if (reply->type == REDIS_REPLY_STRING) {
        std::cout << "Course count: " << reply->str << std::endl;
    }
    freeReplyObject(reply);
    
    reply = (redisReply*)redisCommand(context, "GET completion_rate");
    if (reply->type == REDIS_REPLY_STRING) {
        std::cout << "Completion rate: " << reply->str << std::endl;
    }
    freeReplyObject(reply);
    
    // Free the Redis context
    redisFree(context);
    return 0;
}
// Expected Output:
// Course count: 5
// Completion rate: 95.500000

Let's break down the code:

  • As in the previous lesson, we first include the necessary headers and establish a connection to the Redis server using hiredis.
  • The SET Redis command is used to store numeric values: count with a value of 5 and completion_rate with a value of 95.5. These commands are sent using redisCommand.
  • We retrieve these values with the GET Redis command. The response is fetched into a redisReply object, and we check if the return type is a string before printing the value. Note that numeric values are retrieved as strings, so if you need to perform calculations, you will need to convert them into numeric types using appropriate conversion functions.
  • freeReplyObject is used to free the memory previously occupied by the redisReply object after each command execution.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal