Lesson 1
Managing User Data with Expiration Using Go and Redis
Managing User Data with Expiration

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.

What You'll Build

In this unit, we will implement two primary operations for managing user data using Go:

  1. Adding user data with an expiration time: This ensures that user data is stored only for a specified duration before being automatically deleted.
  2. Retrieving user data: This allows us to fetch the stored user data.

Here is a Go code example to help illustrate these operations:

Go
1package main 2 3import ( 4 "context" 5 "fmt" 6 "time" 7 "github.com/redis/go-redis/v9" 8) 9 10var ctx = context.Background() 11 12func main() { 13 client := redis.NewClient(&redis.Options{ 14 Addr: "localhost:6379", 15 DB: 0, 16 }) 17 18 data := map[string]string{ 19 "email": "user1@example.com", 20 } 21 22 // Add user data with expiration 23 err := client.Set(ctx, "user:1", data["email"], 24*time.Hour).Err() 24 if err != nil { 25 fmt.Println("Error setting user data:", err) 26 return 27 } 28 29 // Retrieve user data 30 val, err := client.Get(ctx, "user:1").Result() 31 if err != nil { 32 fmt.Println("Error retrieving user data:", err) 33 return 34 } 35 fmt.Println("Retrieved user data:", val) 36}

In this example, Set is used to store user data with an expiration time, which is specified as 24*time.Hour to represent a duration of one day. The Get method is used to retrieve the stored data.

This foundational knowledge will prepare you for more complex tasks in upcoming lessons. Let's move on to practice implementing this logic to reinforce your understanding.

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