Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Managing Key Expiration | Advanced Features and Security
Introduction to Redis
course content

Course Content

Introduction to Redis

Introduction to Redis

1. Redis Fundamentals
2. The Essential Redis Commands
3. Data Types in Redis
4. Advanced Features and Security
5. Caching with Redis and Spring Boot

book
Managing Key Expiration

TTL specifies the duration a key remains available in the database. Once this time expires, the key is automatically deleted.

As shown in the example, keys with expired TTLs are removed, while the remaining keys continue to exist in the database with their updated lifespans. This helps optimize memory usage and automate the removal of outdated data.

Setting Key Expiration

You can set the expiration time for a key in several ways. For instance, you can define a key and specify that it will exist for one hour:

Here, the key my_key will be automatically deleted after 3600 seconds (1 hour).

Alternatively, you can combine setting a value and defining the TTL in a single command. For example, to set TTL in seconds or milliseconds:

In the first case, the key will expire in 3600 seconds, and in the second case, it will expire in 60000 milliseconds (1 minute).

Checking the Remaining TTL

To check how much time is left before a key expires, you can use the TTL command:

If the key exists and has a TTL, the command will return the remaining time in seconds. For example, if the result is 120, the key will expire in 2 minutes. If the key has no expiration, the result will be -1, and if the key does not exist, the result will be -2.

For more precise control, you can use milliseconds:

For instance, if the result is 45000, it means the key will expire in 45 seconds.

Removing Key Expiration

If a key should no longer expire automatically, you can remove its TTL:

After this command, the key my_key will become permanent and will not be deleted automatically.

Practical Applications

Key expiration management has a wide range of use cases. For example, in caching, expired records are automatically removed, freeing up memory. For session management, it ensures inactive sessions are terminated, improving both system security and performance.

1. What is the purpose of managing TTL for keys in Redis?

2. What happens when you run the PERSIST command on a key?

What is the purpose of managing TTL for keys in Redis?

What is the purpose of managing TTL for keys in Redis?

Select the correct answer

What happens when you run the `PERSIST` command on a key?

What happens when you run the PERSIST command on a key?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt