Welcome to the first step in building our Redis-based backend system. In this unit, we will focus on how to manage user data with expiration using Redis
. This is a fundamental part of our project that will set the stage for more advanced features in later units.
Let's take a quick look at what you'll be building in this unit. We will focus on two key operations for managing user data:
- Adding user data with an expiration time: This will ensure that user data is stored for a limited period and automatically deleted afterward.
- Retrieving user data: This operation will help us fetch the user data we previously stored.
Here’s how these operations will be implemented:
Java1import redis.clients.jedis.Jedis; 2import com.google.gson.Gson; 3import java.time.Duration; 4 5public class Main { 6 private static final Gson gson = new Gson(); 7 8 public static void main(String[] args) { 9 // Connect to Redis 10 try (Jedis jedis = new Jedis("localhost", 6379)) { 11 // Add and retrieve user data 12 UserData userData = new UserData("Alice", 30, "alice@example.com"); 13 addUser(jedis, 1, userData); 14 UserData retrievedUser = getUser(jedis, 1); 15 System.out.println("User 1: " + retrievedUser); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19 } 20 21 // Function to add user data with expiration 22 public static void addUser(Jedis jedis, int userId, UserData data) { 23 String key = "user:" + userId; 24 String jsonData = gson.toJson(data); 25 jedis.setex(key, (int) Duration.ofDays(1).getSeconds(), jsonData); 26 } 27 28 // Function to retrieve user data 29 public static UserData getUser(Jedis jedis, int userId) { 30 String key = "user:" + userId; 31 String jsonData = jedis.get(key); 32 return jsonData != null ? gson.fromJson(jsonData, UserData.class) : null; 33 } 34}
In this example, the UserData
class is used to represent the user's information. It includes the user’s name, age, and email. Here is the definition of the UserData
class:
Java1public class UserData { 2 private String name; 3 private int age; 4 private String email; 5 6 public UserData(String name, int age, String email) { 7 this.name = name; 8 this.age = age; 9 this.email = email; 10 } 11 12 @Override 13 public String toString() { 14 return "UserData{name='" + name + "', age=" + age + ", email='" + email + "'}"; 15 } 16}
This implementation uses the Jedis
library to interact with Redis. The addUser
method stores user data in Redis with a one-day expiration time using the setex
method. The getUser
method retrieves the user data, deserializing it back into a UserData
object using Gson.
Now that you have a clear idea of what you'll be building, let’s start implementing this functionality and explore how Redis helps manage temporary data effectively. This practice will strengthen your understanding and prepare you for more complex operations in the upcoming units.