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:

Java
// Connect to Redis
Jedis jedis = new Jedis("localhost", 6379);

// Setting numeric values
jedis.set("count", "5");
jedis.set("completion_rate", "95.5");

// Retrieving the values
String count = jedis.get("count");
String completionRate = jedis.get("completion_rate");

System.out.println("Course count: " + count);
System.out.println("Completion rate: " + completionRate);

// Closing the connection
jedis.close();

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:

Course count: 5  
Completion rate: 95.5  

Incrementing Numbers in Redis

Redis allows you to increment numeric values of type int atomically using the incr and incrBy commands.

Java
// Connect to Redis
Jedis jedis = new Jedis("localhost", 6379);

// Setting an initial value
jedis.set("count", "0");

// Incrementing by 1
jedis.incr("count");
System.out.println("After INCR: " + jedis.get("count"));

// Incrementing by a specific value
jedis.incrBy("count", 5);
System.out.println("After INCRBY 5: " + jedis.get("count"));

// Closing the connection
jedis.close();

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:

After INCR: 1  
After INCRBY 5: 6  

Decrementing Numbers in Redis

You can decrement numeric values of type int using the decr and decrBy commands.

Java
// Connect to Redis
Jedis jedis = new Jedis("localhost", 6379);

// Setting an initial value
jedis.set("count", "10");

// Decrementing by 1
jedis.decr("count");
System.out.println("After DECR: " + jedis.get("count"));

// Decrementing by a specific value
jedis.decrBy("count", 3);
System.out.println("After DECRBY 3: " + jedis.get("count"));

// Closing the connection
jedis.close();

In this example:

  • decr("count") decrements the value by 1.
  • decrBy("count", 3) decrements the value by 3.

The output will be:

After DECR: 9  
After DECRBY 3: 6  
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