Created
October 4, 2023 15:37
-
-
Save mhrlife/55872aa7b22881e66024fc32ac0e63f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"github.com/redis/go-redis/v9" | |
"log" | |
"time" | |
) | |
type Post struct { | |
Slug string // the unique identifier | |
Content string | |
} | |
func GetLastNPostsFromDatabase(n int) []Post { | |
var posts []Post | |
for i := 0; i < n; i++ { | |
posts = append(posts, Post{ | |
Slug: fmt.Sprintf("post-%d-slug", i), | |
Content: fmt.Sprintf("Some random content for the post #%d", i), | |
}) | |
} | |
return posts | |
} | |
func FillCacheWithPostsOneByOne(ctx context.Context, rdb *redis.Client, posts []Post) error { | |
for _, post := range posts { | |
// save each post one by one | |
if err := rdb.Set(ctx, fmt.Sprintf("post:%s", post.Slug), post.Content, 0).Err(); err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
func main() { | |
rdb := redis.NewClient(&redis.Options{}) | |
startTime := time.Now() | |
posts := GetLastNPostsFromDatabase(100) | |
if err := FillCacheWithPostsOneByOne(context.Background(), rdb, posts); err != nil { | |
log.Printf("error while filling the cache: %v\n", err) | |
} | |
fmt.Println("took ", time.Since(startTime)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment