Welcome back! Now that you've learned how to work with numbers in Redis using Java, 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's the code snippet that we'll be working with:
-
After setting initial values for
count,completion_rate, andduration, various operations are performed:decr("count")decreases the value ofcountby 1. You can usedecrby("count", 2)to decrementcountby 2. Note thatdecrcan only be used on integer values.incrbyfloat("completion_rate", 1.5)incrementscompletion_rateby 1.5. This method can be used on integers and floating-point values.incr("duration")increases thedurationby 1. You can useincrby("duration", 5)to incrementdurationby 5. Note thatincrcan only be used on integer values.
-
Finally, the values are retrieved to display the updated states with
System.out.println.
It's important to note that the decr and incr operations are atomic, meaning they ensure thread-safe updates even when multiple clients modify the same key simultaneously. These operations can only be performed on keys containing valid integer values. If the key holds a non-integer value, Redis will throw an error. For incrbyfloat, while it supports floating-point arithmetic, be aware of potential precision issues common to floating-point operations due to how numbers are represented in memory.
