Skip to content

Instantly share code, notes, and snippets.

@mhrlife
Created October 4, 2023 15:37
Show Gist options
  • Save mhrlife/55872aa7b22881e66024fc32ac0e63f1 to your computer and use it in GitHub Desktop.
Save mhrlife/55872aa7b22881e66024fc32ac0e63f1 to your computer and use it in GitHub Desktop.
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