move: 后端
This commit is contained in:
58
backend/internal/feed/entity.go
Normal file
58
backend/internal/feed/entity.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package feed
|
||||
|
||||
type FeedAuthor struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
type FeedVideoItem struct {
|
||||
ID uint `json:"id"`
|
||||
Author FeedAuthor `json:"author"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
PlayURL string `json:"play_url"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
LikesCount int64 `json:"likes_count"`
|
||||
IsLiked bool `json:"is_liked"`
|
||||
}
|
||||
|
||||
type ListLatestRequest struct {
|
||||
Limit int `json:"limit"`
|
||||
LatestTime int64 `json:"latest_time"`
|
||||
}
|
||||
|
||||
type ListLatestResponse struct {
|
||||
VideoList []FeedVideoItem `json:"video_list"`
|
||||
NextTime int64 `json:"next_time"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
type ListLikesCountRequest struct {
|
||||
Limit int `json:"limit"`
|
||||
LikesCountBefore *int64 `json:"likes_count_before,omitempty"`
|
||||
IDBefore *uint `json:"id_before,omitempty"`
|
||||
}
|
||||
|
||||
type LikesCountCursor struct {
|
||||
LikesCount int64
|
||||
ID uint
|
||||
}
|
||||
|
||||
type ListLikesCountResponse struct {
|
||||
VideoList []FeedVideoItem `json:"video_list"`
|
||||
NextLikesCountBefore *int64 `json:"next_likes_count_before,omitempty"`
|
||||
NextIDBefore *uint `json:"next_id_before,omitempty"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
type ListByFollowingRequest struct {
|
||||
Limit int `json:"limit"`
|
||||
LatestTime int64 `json:"latest_time"`
|
||||
}
|
||||
|
||||
type ListByFollowingResponse struct {
|
||||
VideoList []FeedVideoItem `json:"video_list"`
|
||||
NextTime int64 `json:"next_time"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
114
backend/internal/feed/handler.go
Normal file
114
backend/internal/feed/handler.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package feed
|
||||
|
||||
import (
|
||||
"feedsystem_video_go/internal/middleware"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type FeedHandler struct {
|
||||
service *FeedService
|
||||
}
|
||||
|
||||
func NewFeedHandler(service *FeedService) *FeedHandler {
|
||||
return &FeedHandler{service: service}
|
||||
}
|
||||
|
||||
func (f *FeedHandler) ListLatest(c *gin.Context) {
|
||||
var req ListLatestRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if req.Limit <= 0 || req.Limit > 50 {
|
||||
req.Limit = 10
|
||||
}
|
||||
var latestTime time.Time
|
||||
if req.LatestTime > 0 {
|
||||
latestTime = time.Unix(req.LatestTime, 0)
|
||||
}
|
||||
viewerAccountID, err := middleware.GetAccountID(c)
|
||||
if err != nil {
|
||||
viewerAccountID = 0
|
||||
}
|
||||
feedItems, err := f.service.ListLatest(c.Request.Context(), req.Limit, latestTime, viewerAccountID)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(200, feedItems)
|
||||
}
|
||||
|
||||
func (f *FeedHandler) ListLikesCount(c *gin.Context) {
|
||||
var req ListLikesCountRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
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, cursor, viewerAccountID)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(200, feedItems)
|
||||
}
|
||||
|
||||
func (f *FeedHandler) ListByFollowing(c *gin.Context) {
|
||||
var req ListByFollowingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if req.Limit <= 0 || req.Limit > 50 {
|
||||
req.Limit = 10
|
||||
}
|
||||
viewerAccountID, err := middleware.GetAccountID(c)
|
||||
if err != nil {
|
||||
viewerAccountID = 0
|
||||
}
|
||||
var latestTime time.Time
|
||||
if req.LatestTime > 0 {
|
||||
latestTime = time.Unix(req.LatestTime, 0)
|
||||
}
|
||||
feedItems, err := f.service.ListByFollowing(c.Request.Context(), req.Limit, latestTime, viewerAccountID)
|
||||
if err != nil {
|
||||
c.JSON(500, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(200, feedItems)
|
||||
}
|
||||
70
backend/internal/feed/repo.go
Normal file
70
backend/internal/feed/repo.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package feed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"feedsystem_video_go/internal/social"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type FeedRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewFeedRepository(db *gorm.DB) *FeedRepository {
|
||||
return &FeedRepository{db: db}
|
||||
}
|
||||
|
||||
func (repo *FeedRepository) ListLatest(ctx context.Context, limit int, latestBefore time.Time) ([]*video.Video, error) {
|
||||
var videos []*video.Video
|
||||
query := repo.db.WithContext(ctx).Model(&video.Video{}).
|
||||
Order("create_time DESC")
|
||||
if !latestBefore.IsZero() {
|
||||
query = query.Where("create_time < ?", latestBefore)
|
||||
}
|
||||
if err := query.Limit(limit).Find(&videos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return videos, nil
|
||||
}
|
||||
|
||||
func (repo *FeedRepository) ListLikesCountWithCursor(ctx context.Context, limit int, cursor *LikesCountCursor) ([]*video.Video, error) {
|
||||
var videos []*video.Video
|
||||
query := repo.db.WithContext(ctx).Model(&video.Video{}).
|
||||
Order("likes_count DESC, id DESC")
|
||||
|
||||
if cursor != nil {
|
||||
query = query.Where(
|
||||
"(likes_count < ?) OR (likes_count = ? AND id < ?)",
|
||||
cursor.LikesCount,
|
||||
cursor.LikesCount, cursor.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if err := query.Limit(limit).Find(&videos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return videos, nil
|
||||
}
|
||||
|
||||
func (repo *FeedRepository) ListByFollowing(ctx context.Context, limit int, viewerAccountID uint, latestBefore time.Time) ([]*video.Video, error) {
|
||||
var videos []*video.Video
|
||||
query := repo.db.WithContext(ctx).Model(&video.Video{}).
|
||||
Order("create_time DESC")
|
||||
if viewerAccountID > 0 {
|
||||
followingSubQuery := repo.db.WithContext(ctx).
|
||||
Model(&social.Social{}).
|
||||
Select("vlogger_id").
|
||||
Where("follower_id = ?", viewerAccountID)
|
||||
query = query.Where("author_id IN (?)", followingSubQuery)
|
||||
}
|
||||
if !latestBefore.IsZero() {
|
||||
query = query.Where("create_time < ?", latestBefore)
|
||||
}
|
||||
if err := query.Limit(limit).Find(&videos).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return videos, nil
|
||||
}
|
||||
256
backend/internal/feed/service.go
Normal file
256
backend/internal/feed/service.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package feed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
rediscache "feedsystem_video_go/internal/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type FeedService struct {
|
||||
repo *FeedRepository
|
||||
likeRepo *video.LikeRepository
|
||||
cache *rediscache.Client
|
||||
cacheTTL time.Duration
|
||||
}
|
||||
|
||||
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) {
|
||||
// 从数据库中查询最新视频
|
||||
doListLatestFromDB := func() (ListLatestResponse, error) {
|
||||
videos, err := f.repo.ListLatest(ctx, limit, latestBefore)
|
||||
if err != nil {
|
||||
return ListLatestResponse{}, err
|
||||
}
|
||||
var nextTime int64
|
||||
if len(videos) > 0 {
|
||||
nextTime = videos[len(videos)-1].CreateTime.Unix()
|
||||
} else {
|
||||
nextTime = 0
|
||||
}
|
||||
hasMore := len(videos) == limit
|
||||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListLatestResponse{}, err
|
||||
}
|
||||
resp := ListLatestResponse{
|
||||
VideoList: feedVideos,
|
||||
NextTime: nextTime,
|
||||
HasMore: hasMore,
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
// 先从缓存中查询
|
||||
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
|
||||
}
|
||||
} else if rediscache.IsMiss(err) { // 缓存未命中
|
||||
lockKey := "lock:" + cacheKey
|
||||
// 缓存未命中,尝试加锁
|
||||
token, locked, _ := f.cache.Lock(cacheCtx, lockKey, 500*time.Millisecond)
|
||||
if locked {
|
||||
defer func() { _ = f.cache.Unlock(context.Background(), lockKey, token) }()
|
||||
if b, err := f.cache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||||
var cached ListLatestResponse
|
||||
if err := json.Unmarshal(b, &cached); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
} else { // 缓存未命中,从数据库中查询
|
||||
resp, err := doListLatestFromDB()
|
||||
if err != nil {
|
||||
return ListLatestResponse{}, err
|
||||
}
|
||||
if b, err := json.Marshal(resp); err == nil {
|
||||
_ = f.cache.SetBytes(cacheCtx, cacheKey, b, f.cacheTTL)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
} else { // 缓存未命中,其他goroutine正在查询,等待
|
||||
for i := 0; i < 5; i++ {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if b, err := f.cache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||||
var cached ListLatestResponse
|
||||
if err := json.Unmarshal(b, &cached); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 缓存中没有查询到结果,从数据库中查询
|
||||
resp, err := doListLatestFromDB()
|
||||
if err != nil {
|
||||
return ListLatestResponse{}, err
|
||||
}
|
||||
// 缓存查询结果
|
||||
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, cursor *LikesCountCursor, viewerAccountID uint) (ListLikesCountResponse, error) {
|
||||
videos, err := f.repo.ListLikesCountWithCursor(ctx, limit, cursor)
|
||||
if err != nil {
|
||||
return ListLikesCountResponse{}, err
|
||||
}
|
||||
hasMore := len(videos) == limit
|
||||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListLikesCountResponse{}, err
|
||||
}
|
||||
resp := ListLikesCountResponse{
|
||||
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
|
||||
}
|
||||
|
||||
// 按照关注列表查询视频
|
||||
func (f *FeedService) ListByFollowing(ctx context.Context, limit int, latestBefore time.Time, viewerAccountID uint) (ListByFollowingResponse, error) {
|
||||
doListByFollowingFromDB := func() (ListByFollowingResponse, error) {
|
||||
videos, err := f.repo.ListByFollowing(ctx, limit, viewerAccountID, latestBefore)
|
||||
if err != nil {
|
||||
return ListByFollowingResponse{}, err
|
||||
}
|
||||
var nextTime int64
|
||||
if len(videos) > 0 {
|
||||
nextTime = videos[len(videos)-1].CreateTime.Unix()
|
||||
} else {
|
||||
nextTime = 0
|
||||
}
|
||||
hasMore := len(videos) == limit
|
||||
feedVideos, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
|
||||
if err != nil {
|
||||
return ListByFollowingResponse{}, err
|
||||
}
|
||||
resp := ListByFollowingResponse{
|
||||
VideoList: feedVideos,
|
||||
NextTime: nextTime,
|
||||
HasMore: hasMore,
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
var cacheKey string
|
||||
if viewerAccountID != 0 && f.cache != nil {
|
||||
before := int64(0)
|
||||
if !latestBefore.IsZero() {
|
||||
before = latestBefore.Unix()
|
||||
}
|
||||
cacheKey = fmt.Sprintf("feed:listByFollowing:limit=%d:accountID=%d:before=%d", limit, viewerAccountID, before)
|
||||
cacheCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
b, err := f.cache.GetBytes(cacheCtx, cacheKey)
|
||||
if err == nil {
|
||||
var cached ListByFollowingResponse
|
||||
if err := json.Unmarshal(b, &cached); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
} else if rediscache.IsMiss(err) { // 缓存未命中
|
||||
lockKey := "lock:" + cacheKey
|
||||
// 缓存未命中,尝试加锁
|
||||
token, locked, _ := f.cache.Lock(cacheCtx, lockKey, 500*time.Millisecond)
|
||||
if locked {
|
||||
defer func() { _ = f.cache.Unlock(context.Background(), lockKey, token) }()
|
||||
if b, err := f.cache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||||
var cached ListByFollowingResponse
|
||||
if err := json.Unmarshal(b, &cached); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
} else { // 缓存未命中,从数据库中查询
|
||||
resp, err := doListByFollowingFromDB()
|
||||
if err != nil {
|
||||
return ListByFollowingResponse{}, err
|
||||
}
|
||||
if b, err := json.Marshal(resp); err == nil {
|
||||
_ = f.cache.SetBytes(cacheCtx, cacheKey, b, f.cacheTTL)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < 5; i++ {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if b, err := f.cache.GetBytes(cacheCtx, cacheKey); err == nil {
|
||||
var cached ListByFollowingResponse
|
||||
if err := json.Unmarshal(b, &cached); err == nil {
|
||||
return cached, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := doListByFollowingFromDB()
|
||||
if err != nil {
|
||||
return ListByFollowingResponse{}, err
|
||||
}
|
||||
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) buildFeedVideos(ctx context.Context, videos []*video.Video, viewerAccountID uint) ([]FeedVideoItem, error) {
|
||||
feedVideos := make([]FeedVideoItem, 0, len(videos))
|
||||
videoIDs := make([]uint, len(videos))
|
||||
for i, v := range videos {
|
||||
videoIDs[i] = v.ID
|
||||
}
|
||||
likedMap, err := f.likeRepo.BatchGetLiked(ctx, videoIDs, viewerAccountID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, video := range videos {
|
||||
feedVideos = append(feedVideos, FeedVideoItem{
|
||||
ID: video.ID,
|
||||
Author: FeedAuthor{ID: video.AuthorID, Username: video.Username},
|
||||
Title: video.Title,
|
||||
Description: video.Description,
|
||||
PlayURL: video.PlayURL,
|
||||
CoverURL: video.CoverURL,
|
||||
CreateTime: video.CreateTime.Unix(),
|
||||
LikesCount: video.LikesCount,
|
||||
IsLiked: likedMap[video.ID],
|
||||
})
|
||||
}
|
||||
return feedVideos, nil
|
||||
}
|
||||
Reference in New Issue
Block a user