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.
In this lesson, you will learn how to:
- Set numeric values in Redis.
- Retrieve and print numeric values.
Here's the code snippet that we'll be working with:
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 of5
andcompletion_rate
with a value of95.5
. These commands are sent usingredisCommand
. - We retrieve these values with the
GET
Redis command. The response is fetched into aredisReply
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 theredisReply
object after each command execution.
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
:
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.
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!
