Managing Key Expiration in Redis with Java

Managing Key Expiration

Welcome back! In this lesson, we will explore a crucial feature of Redis: key expiration. This topic builds on our Redis knowledge and adds another tool to our kit for managing data efficiently in high-performance applications.

What You'll Learn

You will learn how to set expiration times on your Redis keys using Java. This is useful for many situations, such as caching data, managing session lifetimes, or any scenario where you want data to automatically expire after a certain period. We will learn how to set expiration times on keys and check the remaining time-to-live (TTL) for a key.

Here's a quick preview of what you will be doing:

To set a key with an expiration time, you can use the set method with the EX parameter in Lettuce:

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class KeyExpirationExample {
    public static void main(String[] args) throws InterruptedException {
        RedisClient redisClient = RedisClient.create("redis://localhost:6379/");
        StatefulRedisConnection<String, String> connection = redisClient.connect();
        RedisCommands<String, String> commands = connection.sync();

        String key = "session:12345";
        commands.setex(key, 2, "data");

        Long ttl = commands.ttl(key);
        System.out.println("Time-to-live for session key: " + ttl + " seconds");

        Thread.sleep(3000);
        String value = commands.get(key);
        System.out.println("Value: " + value);  // null

        connection.close();
        redisClient.shutdown();
    }
}

The above code snippet shows how to set a key (session:12345) with a value (data) that expires after 2 seconds using the Lettuce API.

To check the remaining time-to-live (TTL) for a key, you can use the ttl method with the key name as the parameter.

After waiting for the expiration time, you can verify that the key no longer exists. This code waits 3 seconds and then attempts to get the value of the key, which should return null because the key has expired.

Another useful method is expire, which allows you to set the expiration time for a key after it has been created:

Java
commands.set(key, "data");
commands.expire(key, 2);

This code snippet sets the key session:12345 with a value of data and then sets the expiration time to 2 seconds. We will explore this method in more detail in the practice section.

It's important to note that Redis uses a lazy expiration mechanism, meaning keys are not immediately removed once they expire but are removed when accessed or during periodic cleanup by the server. This ensures performance remains optimal but may result in some expired keys lingering for a short time.

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