feat: 添加了redis缓存

This commit is contained in:
Leon
2025-12-23 02:26:29 +08:00
parent a632768ef8
commit a98e9d28f0
4 changed files with 142 additions and 19 deletions

View File

@@ -49,11 +49,38 @@ func (f *FeedHandler) ListLikesCount(c *gin.Context) {
if req.Limit <= 0 || req.Limit > 50 {
req.Limit = 10
}
var cursor *LikesCountCursor
if req.LikesCountBefore != nil || req.IDBefore != nil {
if req.LikesCountBefore == nil || req.IDBefore == nil {
c.JSON(400, gin.H{"error": "likes_count_before and id_before must be provided together"})
return
}
likesCountBefore := *req.LikesCountBefore
idBefore := *req.IDBefore
if likesCountBefore < 0 {
c.JSON(400, gin.H{"error": "invalid cursor: likes_count_before must be >= 0"})
return
}
if idBefore == 0 {
if likesCountBefore != 0 {
c.JSON(400, gin.H{"error": "invalid cursor: id_before must be > 0"})
return
}
} else {
cursor = &LikesCountCursor{
LikesCount: likesCountBefore,
ID: idBefore,
}
}
}
viewerAccountID, err := middleware.GetAccountID(c)
if err != nil {
viewerAccountID = 0
}
feedItems, err := f.service.ListLikesCount(c.Request.Context(), req.Limit, req.LikesCount, viewerAccountID)
feedItems, err := f.service.ListLikesCount(c.Request.Context(), req.Limit, cursor, viewerAccountID)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return

View File

@@ -2,20 +2,45 @@ package feed
import (
"context"
"encoding/json"
"feedsystem_video_go/internal/video"
"fmt"
rediscache "feedsystem_video_go/internal/redis"
"time"
)
type FeedService struct {
repo *FeedRepository
likeRepo *video.LikeRepository
cache *rediscache.Client
cacheTTL time.Duration
}
func NewFeedService(repo *FeedRepository, likeRepo *video.LikeRepository) *FeedService {
return &FeedService{repo: repo, likeRepo: likeRepo}
func NewFeedService(repo *FeedRepository, likeRepo *video.LikeRepository, cache *rediscache.Client) *FeedService {
return &FeedService{repo: repo, likeRepo: likeRepo, cache: cache, cacheTTL: 5 * time.Second}
}
func (f *FeedService) ListLatest(ctx context.Context, limit int, latestBefore time.Time, viewerAccountID uint) (ListLatestResponse, error) {
var cacheKey string
if viewerAccountID == 0 && f.cache != nil {
before := int64(0)
if !latestBefore.IsZero() {
before = latestBefore.Unix()
}
cacheKey = fmt.Sprintf("feed:listLatest:limit=%d:before=%d", limit, before)
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
b, err := f.cache.GetBytes(cacheCtx, cacheKey)
if err == nil {
var cached ListLatestResponse
if err := json.Unmarshal(b, &cached); err == nil {
return cached, nil
}
}
}
videos, err := f.repo.ListLatest(ctx, limit, latestBefore)
if err != nil {
return ListLatestResponse{}, err
@@ -55,20 +80,22 @@ func (f *FeedService) ListLatest(ctx context.Context, limit int, latestBefore ti
NextTime: nextTime,
HasMore: hasMore,
}
if cacheKey != "" {
if b, err := json.Marshal(resp); err == nil {
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_ = f.cache.SetBytes(cacheCtx, cacheKey, b, f.cacheTTL)
}
}
return resp, nil
}
func (f *FeedService) ListLikesCount(ctx context.Context, limit int, likesCountBefore int64, viewerAccountID uint) (ListLikesCountResponse, error) {
videos, err := f.repo.ListLikesCount(ctx, limit, likesCountBefore)
func (f *FeedService) ListLikesCount(ctx context.Context, limit int, cursor *LikesCountCursor, viewerAccountID uint) (ListLikesCountResponse, error) {
videos, err := f.repo.ListLikesCountWithCursor(ctx, limit, cursor)
if err != nil {
return ListLikesCountResponse{}, err
}
var nextLikesCountBefore int64
if len(videos) > 0 {
nextLikesCountBefore = videos[len(videos)-1].LikesCount
} else {
nextLikesCountBefore = 0
}
hasMore := len(videos) == limit
feedVideos := make([]FeedVideoItem, 0, len(videos))
for _, video := range videos {
@@ -88,14 +115,21 @@ func (f *FeedService) ListLikesCount(ctx context.Context, limit int, likesCountB
Description: video.Description,
PlayURL: video.PlayURL,
CoverURL: video.CoverURL,
CreateTime: video.CreateTime.Unix(),
LikesCount: video.LikesCount,
IsLiked: isLiked,
})
}
resp := ListLikesCountResponse{
VideoList: feedVideos,
NextLikesCountBefore: nextLikesCountBefore,
HasMore: hasMore,
VideoList: feedVideos,
HasMore: hasMore,
}
if len(videos) > 0 {
last := videos[len(videos)-1]
nextLikesCountBefore := last.LikesCount
nextIDBefore := last.ID
resp.NextLikesCountBefore = &nextLikesCountBefore
resp.NextIDBefore = &nextIDBefore
}
return resp, nil
}
@@ -130,6 +164,7 @@ func (f *FeedService) ListByFollowing(ctx context.Context, limit int, viewerAcco
Description: video.Description,
PlayURL: video.PlayURL,
CoverURL: video.CoverURL,
CreateTime: video.CreateTime.Unix(),
LikesCount: video.LikesCount,
IsLiked: isLiked,
})

View File

@@ -4,6 +4,7 @@ import (
"feedsystem_video_go/internal/account"
"feedsystem_video_go/internal/feed"
"feedsystem_video_go/internal/middleware"
rediscache "feedsystem_video_go/internal/redis"
"feedsystem_video_go/internal/social"
"feedsystem_video_go/internal/video"
@@ -11,7 +12,7 @@ import (
"gorm.io/gorm"
)
func SetRouter(db *gorm.DB) *gin.Engine {
func SetRouter(db *gorm.DB, cache *rediscache.Client) *gin.Engine {
r := gin.Default()
// account
accountRepository := account.NewAccountRepository(db)
@@ -50,9 +51,6 @@ func SetRouter(db *gorm.DB) *gin.Engine {
likeService := video.NewLikeService(likeRepository, videoRepository)
likeHandler := video.NewLikeHandler(likeService)
likeGroup := r.Group("/like")
{
likeGroup.POST("/getLikesCount", likeHandler.GetLikesCount)
}
protectedLikeGroup := likeGroup.Group("")
protectedLikeGroup.Use(middleware.JWTAuth(accountRepository))
{
@@ -89,7 +87,7 @@ func SetRouter(db *gorm.DB) *gin.Engine {
}
// feed
feedRepository := feed.NewFeedRepository(db)
feedService := feed.NewFeedService(feedRepository, likeRepository)
feedService := feed.NewFeedService(feedRepository, likeRepository, cache)
feedHandler := feed.NewFeedHandler(feedService)
feedGroup := r.Group("/feed")
feedGroup.Use(middleware.SoftJWTAuth(accountRepository))

63
internal/redis/cache.go Normal file
View File

@@ -0,0 +1,63 @@
package redis
import (
"context"
"os"
"strconv"
"time"
redis "github.com/redis/go-redis/v9"
)
type Client struct {
rdb *redis.Client
}
func NewFromEnv() (*Client, error) {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
addr = "127.0.0.1:6379"
}
db := 0
if v := os.Getenv("REDIS_DB"); v != "" {
n, err := strconv.Atoi(v)
if err != nil {
return nil, err
}
db = n
}
rdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: os.Getenv("REDIS_PASSWORD"),
DB: db,
})
return &Client{rdb: rdb}, nil
}
func (c *Client) Close() error {
if c == nil || c.rdb == nil {
return nil
}
return c.rdb.Close()
}
func (c *Client) Ping(ctx context.Context) error {
if c == nil || c.rdb == nil {
return nil
}
return c.rdb.Ping(ctx).Err()
}
func (c *Client) GetBytes(ctx context.Context, key string) ([]byte, error) {
return c.rdb.Get(ctx, key).Bytes()
}
func (c *Client) SetBytes(ctx context.Context, key string, value []byte, ttl time.Duration) error {
return c.rdb.Set(ctx, key, value, ttl).Err()
}
func IsMiss(err error) bool {
return err == redis.Nil
}