Lesson 2
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:

C++
1#include <iostream> 2#include <hiredis/hiredis.h> 3 4int main() { 5 // Connect to Redis 6 redisContext* context = redisConnect("127.0.0.1", 6379); 7 if (context == NULL || context->err) { 8 if (context) { 9 std::cerr << "Error: " << context->errstr << std::endl; 10 // handle error 11 } else { 12 std::cerr << "Can't allocate redis context" << std::endl; 13 } 14 return 1; 15 } 16 17 // Setting numeric values 18 redisReply* reply; 19 reply = (redisReply*)redisCommand(context, "SET count %d", 5); 20 freeReplyObject(reply); 21 reply = (redisReply*)redisCommand(context, "SET completion_rate %f", 95.5); 22 freeReplyObject(reply); 23 24 // Getting numeric values 25 reply = (redisReply*)redisCommand(context, "GET count"); 26 if (reply->type == REDIS_REPLY_STRING) { 27 std::cout << "Course count: " << reply->str << std::endl; 28 } 29 freeReplyObject(reply); 30 31 reply = (redisReply*)redisCommand(context, "GET completion_rate"); 32 if (reply->type == REDIS_REPLY_STRING) { 33 std::cout << "Completion rate: " << reply->str << std::endl; 34 } 35 freeReplyObject(reply); 36 37 // Free the Redis context 38 redisFree(context); 39 return 0; 40} 41// Expected Output: 42// Course count: 5 43// 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.
Using MGET for Efficient Multiple Value Retrieval

While the basic GET command works well for single values, Redis provides the MGET command for retrieving multiple values efficiently. Understanding when to use each is important for optimal performance:

  • Use GET when:

    • You only need to retrieve a single value
    • The keys you need are determined dynamically and retrieved one at a time
    • You want slightly better performance for single key retrieval
  • Use MGET when:

    • You need to retrieve multiple known keys at once
    • You want to reduce network overhead by making a single connection instead of multiple connections
    • Performance at scale is crucial (especially in high-traffic applications)

Here's an example using MGET:

C++
1#include <iostream> 2#include <hiredis/hiredis.h> 3 4int main() { 5 redisContext* context = redisConnect("127.0.0.1", 6379); 6 if (context == NULL || context->err) { 7 return -1; 8 } 9 10 // Setting multiple values 11 redisCommand(context, "SET course_1 101"); 12 redisCommand(context, "SET course_2 202"); 13 redisCommand(context, "SET course_3 303"); 14 15 redisReply* reply = (redisReply*)redisCommand(context, "MGET course_1 course_2 course_3"); 16 17 std::cout << "Courses IDs: "; 18 for (size_t i = 0; i < reply->elements; i++) { 19 if (reply->element[i]->str) { 20 std::cout << reply->element[i]->str << " "; 21 } else { 22 std::cout << "nil "; 23 } 24 } 25 std::cout << std::endl; 26 27 freeReplyObject(reply); 28 redisFree(context); 29 return 0; 30} 31// Expected Output: 32// Courses IDs: 101 202 303

The key advantage of MGET is its ability to retrieve multiple values in a single network round-trip. This becomes particularly important in distributed systems where network latency can significantly impact performance. However, for simple applications or single key retrieval, the standard GET command is perfectly suitable and slightly more efficient.

Why It Matters

Working with numbers in Redis is crucial because many real-world applications involve numeric data. From tracking user statistics to monitoring system performance, managing numbers in Redis allows you to perform a variety of useful operations efficiently. By mastering these basic operations with numbers, you'll be well-prepared to tackle more complex tasks and optimize your applications.

Ready to dive in? Let's move on to the practice section and gain hands-on experience working with numbers in Redis!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.