Welcome back! Now that you've learned how to work with numbers in Redis, it's time to build on that knowledge and explore some basic operations with these numbers. This lesson will show you how to perform operations like incrementing, decrementing, and modifying numeric values directly in Redis.
In this lesson, you will learn how to:
- Increment and decrement numeric values.
- Modify numeric values using operations such as increments by a floating point.
Here is a C++ code snippet that demonstrates how to perform these operations using Boost.Redis:
-
Setting Initial Values:
The code first sets initial values forcount,completion_rate, anddurationusing theSETcommand. -
Performing Numeric Operations:
DECR countdecreases the value ofcountby 1 and returns the new value asstd::int64_t.
You can also decrement by a specific value usingDECRBY count 2to decrease it by 2.INCRBYFLOAT completion_rate 1.5increasescompletion_rateby 1.5 and returns the new value asdouble.
This command works with both integer and floating-point values.INCR durationincreases the value ofdurationby 1 and returns the new value asstd::int64_t.
You can increment by a specific value usingINCRBY duration 5to increase it by 5.
-
Retrieving Updated Values: The code then retrieves the updated values for , , and using the command.
Understanding how to perform operations with numbers in Redis is essential for real-world applications. For example, if you are building a learning management system, you might need to track user progress, completion rates, and time spent on courses. Redis makes it fast and easy to update these numbers in real time.
By using type-safe decoders for numeric operations, you leverage Boost.Redis's compile-time type checking, ensuring that your code handles integers and floating-point values correctly without manual string conversions.
By the end of this lesson, you'll be comfortable with basic numeric operations in Redis, preparing you for more advanced tasks. Ready to get started? Let's dive into the practice section and enhance your Redis skills!
