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:

  • count with a value of 5.
  • completion_rate with a value of 95.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 of count by 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:

Atomicity in Redis

Redis operations like INCR, DECR, INCRBY, and DECRBY are atomic. This means that Redis guarantees each operation is performed in a single, indivisible step, ensuring consistency even when multiple clients access the same key simultaneously.

For example, if two clients try to increment the same key at the same time:

  • Redis ensures both increments are applied safely without overwriting each other.
  • You don’t need to implement locks or manual synchronization since Redis handles it for you.

Atomicity is critical in applications where accuracy and concurrency matter, such as counters, analytics, or real-time monitoring. This feature makes Redis highly reliable for handling concurrent numeric operations.

By mastering these operations and understanding Redis's atomicity guarantees, you’ll be able to implement robust and efficient systems that involve numeric data.

Conclusion and Next Steps

You've now learned how to work with numbers in Redis by setting, incrementing, and decrementing them. You also learned about Redis's atomicity guarantees, which ensure consistency and reliability in numerical operations. Up next is a practice section where you’ll apply these concepts hands-on to reinforce your understanding.

Let’s dive in and put what you've learned into practice!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal