From f524123ea66d8038f088187fc8e51d10249979f4 Mon Sep 17 00:00:00 2001 From: Leon <147289645+LeoninCS@users.noreply.github.com> Date: Tue, 23 Dec 2025 19:04:24 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E4=B8=BAvideo=E7=9A=84getdetail=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0redis=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/http/router.go | 2 +- internal/video/video_service.go | 35 ++++++++++++++++++++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/internal/http/router.go b/internal/http/router.go index 55fdb41..3fabb0d 100644 --- a/internal/http/router.go +++ b/internal/http/router.go @@ -34,7 +34,7 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client) *gin.Engine { } // video videoRepository := video.NewVideoRepository(db) - videoService := video.NewVideoService(videoRepository) + videoService := video.NewVideoService(videoRepository, cache) videoHandler := video.NewVideoHandler(videoService, accountService) videoGroup := r.Group("/video") { diff --git a/internal/video/video_service.go b/internal/video/video_service.go index 2d6eb29..7399eaa 100644 --- a/internal/video/video_service.go +++ b/internal/video/video_service.go @@ -2,15 +2,22 @@ package video import ( "context" + "encoding/json" "errors" + "fmt" + "time" + + rediscache "feedsystem_video_go/internal/redis" ) type VideoService struct { - repo *VideoRepository + repo *VideoRepository + cache *rediscache.Client + cacheTTL time.Duration } -func NewVideoService(repo *VideoRepository) *VideoService { - return &VideoService{repo: repo} +func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService { + return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute} } func (vs *VideoService) Publish(ctx context.Context, video *Video) error { @@ -52,10 +59,32 @@ func (vs *VideoService) ListByAuthorID(ctx context.Context, authorID uint) ([]Vi } func (vs *VideoService) GetDetail(ctx context.Context, id uint) (*Video, error) { + if vs.cache != nil { + cacheKey := fmt.Sprintf("video:detail:id=%d", id) + cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond) + defer cancel() + + if b, err := vs.cache.GetBytes(cacheCtx, cacheKey); err == nil { + var cached Video + if err := json.Unmarshal(b, &cached); err == nil { + return &cached, nil + } + } + } + video, err := vs.repo.GetByID(ctx, id) if err != nil { return nil, err } + + if vs.cache != nil { + cacheKey := fmt.Sprintf("video:detail:id=%d", id) + if b, err := json.Marshal(video); err == nil { + cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond) + defer cancel() + _ = vs.cache.SetBytes(cacheCtx, cacheKey, b, vs.cacheTTL) + } + } return video, nil }