Lesson 1
Managing User Data with Expiration Using Lettuce in Java
What You'll Build

In this unit, we'll demonstrate how to manage user data with expiration using Java. You will be employing Lettuce as your primary Redis client library. The lesson will cover two main operations for user data management:

  1. Adding user data with an expiration time: This operation ensures user data is available for a limited time and is automatically deleted afterward. Redis handles expired keys by deleting them when accessed after expiration (lazy deletion) and by periodically scanning and removing them in the background (active expiration) to free up memory.
  2. Retrieving user data: This operation will facilitate fetching the stored user data.

Here’s an example of how we will structure these operations in Java using Lettuce:

Java
1import io.lettuce.core.RedisClient; 2import io.lettuce.core.api.StatefulRedisConnection; 3import io.lettuce.core.api.sync.RedisCommands; 4import java.time.Duration; 5 6public class UserDataManager { 7 public static void main(String[] args) { 8 // Connect to Redis server 9 RedisClient redisClient = RedisClient.create("redis://localhost:6379"); 10 StatefulRedisConnection<String, String> connection = redisClient.connect(); 11 RedisCommands<String, String> syncCommands = connection.sync(); 12 13 // User data to store 14 String userKey = "user:1"; 15 String userData = "{\"email\": \"user1@example.com\"}"; 16 17 // Add user data with expiration time of 1 day 18 syncCommands.setex(userKey, Duration.ofDays(1).getSeconds(), userData); 19 20 // Retrieve user data 21 String retrievedData = syncCommands.get(userKey); 22 System.out.println(retrievedData); 23 24 // Close the connection 25 connection.close(); 26 redisClient.shutdown(); 27 } 28}

Here, we've introduced the setex method to store the user data along with a specified expiration period of one day. Redis manages expiration internally by maintaining a timestamp for when a key is supposed to expire. When the expiration time is reached, the key is automatically deleted from the database.

The get method helps to retrieve the user information we stored earlier.

Now that you have this Java-based template, let's move to the practice section where you can implement and experiment with this logic, enhancing your command over data management in Redis using Lettuce.

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