Lesson 2
Managing Key Expiration with Redis and C++
Managing Key Expiration with C++

Welcome back! In this lesson, we will explore a crucial feature of Redis: key expiration, using the hiredis library in C++. 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 the hiredis library in C++. 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 using Redis commands.

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

To set a key with an expiration time, we use the SET command with the EX option and redisCommand for execution:

C++
1#include <iostream> 2#include <hiredis/hiredis.h> 3#include <chrono> 4#include <thread> 5 6int main() { 7 // Connect to the Redis server 8 redisContext* context = redisConnect("127.0.0.1", 6379); 9 if (context == nullptr || context->err) { 10 if (context) { 11 std::cerr << "Connection error: " << context->errstr << std::endl; 12 } else { 13 std::cerr << "Connection error: can't allocate Redis context" << std::endl; 14 } 15 return 1; 16 } 17 18 // Set a key with an expiration time of 2 seconds 19 const char* key = "session:12345"; 20 redisReply* reply = (redisReply*)redisCommand(context, "SET %s %s EX %d", key, "data", 2); 21 freeReplyObject(reply); 22 23 // Check the time-to-live (TTL) for the key 24 reply = (redisReply*)redisCommand(context, "TTL %s", key); 25 if (reply->type == REDIS_REPLY_INTEGER) { 26 std::cout << "Time-to-live for session key: " << reply->integer << " seconds." << std::endl; 27 } 28 freeReplyObject(reply); 29 // Get the key before expiration 30 reply = (redisReply*)redisCommand(context, "GET %s", key); 31 if (reply->type != REDIS_REPLY_NIL) { 32 std::cout << reply->str << std::endl; 33 } else { 34 std::cout << "Unexpected return value." << std::endl; 35 } 36 // Sleep for 3 seconds, longer than expiration to check the key status 37 std::this_thread::sleep_for(std::chrono::seconds(3)); 38 39 // Try to get the key after expiration 40 reply = (redisReply*)redisCommand(context, "GET %s", key); 41 if (reply->type == REDIS_REPLY_NIL) { 42 std::cout << "Value: None" << std::endl; // The key no longer exists 43 } else { 44 std::cout << "Unexpected return value." << std::endl; 45 } 46 freeReplyObject(reply); 47 48 // Free the context 49 redisFree(context); 50 51 return 0; 52} 53 54//Output 55// Time-to-live for session key: 2 seconds. 56// data 57// Value: None

The above code snippet shows how to set a key (session:12345) with a value (data) that expires after 2 seconds and verify that it no longer exists after the expiration time. The TTL command is used to get the remaining expiration time for the key. The redisCommand function sends this command to the Redis server, and reply->integer retrieves the TTL value if the command execution is successful, indicated by reply->type being REDIS_REPLY_INTEGER. This value denotes how many seconds the key has left before it expires.

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

Plain text
1redisReply* reply = (redisReply*)redisCommand(context, "SET %s %s", key, "data"); 2freeReplyObject(reply); 3 4reply = (redisReply*)redisCommand(context, "EXPIRE %s %d", key, 2); 5freeReplyObject(reply);

This demonstrates how to set an expiration for a previously created key. We will explore this method thoroughly in our practice section.

Why It Matters

Key expiration is an essential feature for managing limited memory resources efficiently. By setting expiration times, you can ensure that outdated data is removed automatically without manual intervention. This can significantly improve your application's performance and reliability.

By mastering key expiration, you can build more intelligent caching mechanisms, manage user sessions effectively, and handle temporary data seamlessly. This concept is a critical aspect of maintaining high-performance applications that need to run efficiently over time.

Exciting, right? Let's move on to the practice section and start applying these concepts hands-on.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.