Working with Numbers in Redis
Working with Numbers
Welcome back to our Redis course! Now that you know how to connect to a Redis server using Java, it's time to move forward and explore how to work with numbers in Redis. In this unit, you’ll learn how to set, increment, and decrement numeric values while also understanding Redis's atomicity guarantees. These concepts are critical for managing counters and performing real-time updates.
Setting Numbers in Redis
Redis treats all values as strings, but you can store numbers and perform numeric operations on them directly. Here’s how you can set numeric values in Redis and retrieve them:
Here, we connect to the Redis server and use the set command to store two numeric values:
countwith a value of5.completion_ratewith a value of95.5.
The get method retrieves these values, and since Redis stores everything as strings, no special handling is required.
The output will be:
Incrementing Numbers in Redis
Redis allows you to increment numeric values of type int atomically using the incr and incrBy commands.
Here’s what happens:
incr("count")increments the value ofcountby 1.incrBy("count", 5)increments the value by 5.
The output will be:
Decrementing Numbers in Redis
You can decrement numeric values of type int using the decr and decrBy commands.
In this example:
decr("count")decrements the value by 1.decrBy("count", 3)decrements the value by 3.
The output will be:
