Skip to content

Commit

Permalink
Add redis to video-service
Browse files Browse the repository at this point in the history
  • Loading branch information
reeered committed Sep 9, 2023
1 parent f1109f4 commit 18e9a02
Show file tree
Hide file tree
Showing 7 changed files with 367 additions and 21 deletions.
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ module toktik
go 1.20

require (
github.com/alicebob/miniredis/v2 v2.30.5
github.com/cloudwego/fastpb v0.0.4
github.com/cloudwego/hertz v0.6.6
github.com/cloudwego/kitex v0.6.2
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fsnotify/fsnotify v1.6.0
github.com/glebarez/sqlite v1.9.0
github.com/go-redis/redis/v7 v7.4.1
github.com/golang/mock v1.6.0
github.com/hashicorp/consul/api v1.20.0
github.com/hertz-contrib/cors v0.0.0-20230423034624-2bc83a8400f0
Expand All @@ -26,6 +28,7 @@ require (
)

require (
github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect
github.com/apache/thrift v0.13.0 // indirect
github.com/armon/go-metrics v0.4.0 // indirect
github.com/aws/aws-sdk-go v1.38.20 // indirect
Expand Down Expand Up @@ -76,6 +79,8 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/nyaruka/phonenumbers v1.0.55 // indirect
github.com/oleiade/lane v1.0.1 // indirect
github.com/onsi/ginkgo v1.14.2 // indirect
github.com/onsi/gomega v1.10.4 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
Expand All @@ -89,6 +94,7 @@ require (
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/u2takey/go-utils v0.3.1 // indirect
github.com/yuin/gopher-lua v1.1.0 // indirect
golang.org/x/arch v0.2.0 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/net v0.10.0 // indirect
Expand Down
5 changes: 4 additions & 1 deletion internal/video/etc/config.yaml.sample
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,7 @@ RabbitMQ:
Password: "Aa112211"
Queue: "publish"
Exchange: "default"
Routing_Key: "publish"
Routing_Key: "publish"
Redis:
Addr: "localhost:6379"
Password: "123456"
4 changes: 3 additions & 1 deletion internal/video/pkg/ctx/ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"toktik/pkg/config"
"toktik/pkg/db"
"toktik/pkg/rabbitmq"
"toktik/pkg/redis"
)

// ServiceContext contains the components required by the service.
Expand All @@ -30,6 +31,7 @@ type ServiceContext struct {
// NewServiceContext initialize the components and returns a new ServiceContext instance.
func NewServiceContext() *ServiceContext {
db.Init()
redis.Init()
minioClient, err := minio.New(
config.Conf.GetString(config.KEY_MINIO_ENDPOINT),
config.Conf.GetString(config.KEY_MINIO_ACCESS_KEY),
Expand Down Expand Up @@ -58,7 +60,7 @@ func NewServiceContext() *ServiceContext {
}

return &ServiceContext{
VideoService: video.NewVideoService(db.Instance),
VideoService: video.NewVideoService(db.Instance, redis.RdbVideos),
MinioClient: minioClient,
UserClient: user.MustNewClient("user", client.WithResolver(r), client.WithRPCTimeout(time.Second*3)),
FavoriteClient: favorite.MustNewClient("favorite", client.WithResolver(r), client.WithRPCTimeout(time.Second*3)),
Expand Down
107 changes: 93 additions & 14 deletions internal/video/pkg/video/video.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package video

import (
"fmt"
"strconv"
"time"

"github.com/go-redis/redis/v7"
"gorm.io/gorm"

"toktik/pkg/db/model"
Expand All @@ -11,43 +14,119 @@ import (
type Video = model.Video

type VideoService struct {
dbInstance func() *gorm.DB
dbInstance func() *gorm.DB
redisClient func() *redis.Client
}

func NewVideoService(db func() *gorm.DB) *VideoService {
func NewVideoService(db func() *gorm.DB, rdb func() *redis.Client) *VideoService {
return &VideoService{
dbInstance: db,
dbInstance: db,
redisClient: rdb,
}
}

func (s *VideoService) CreateVideo(userId int64, title, playUrl, coverUrl string) error {
db := s.dbInstance()
rdb := s.redisClient()

return db.Create(&Video{
video := &Video{
UserId: userId,
Title: title,
PlayUrl: playUrl,
CoverUrl: coverUrl,
}).Error
}

if err := db.Create(video).Error; err != nil {
return err
}

key := fmt.Sprintf("video:%d", video.Id) // 使用视频的唯一标识作为 Redis 键

return rdb.HSet(key, map[string]interface{}{
"Id": video.Id,
"UserId": video.UserId,
"Title": video.Title,
"PlayUrl": video.PlayUrl,
"CoverUrl": video.CoverUrl,
"CreatedAt": video.CreatedAt,
}).Err()
}

func (s *VideoService) ListVideoByUserId(userId int64) ([]*Video, error) {
db := s.dbInstance()
rdb := s.redisClient()

videos := make([]*Video, 0)
if err := db.Where("user_id = ?", userId).Find(&videos).Error; err != nil {
keys, err := rdb.Keys("video:*").Result()
if err != nil {
return nil, err
}

videos := make([]*Video, 0, len(keys))
for _, key := range keys {
videoData, err := rdb.HGetAll(key).Result()
if err != nil {
return nil, err
}

// 解析videoData
videoId, _ := strconv.ParseInt(videoData["Id"], 10, 64)
userIdFromData, _ := strconv.ParseInt(videoData["UserId"], 10, 64)
title := videoData["Title"]
playUrl := videoData["PlayUrl"]
coverUrl := videoData["CoverUrl"]
createdAtStr := videoData["CreatedAt"]
createdAt, err := time.Parse(time.RFC3339, createdAtStr)
if err != nil {
return nil, err
}

// 检查 UserId 是否匹配
if userIdFromData == userId {
video := &Video{
Id: videoId,
UserId: userIdFromData,
Title: title,
PlayUrl: playUrl,
CoverUrl: coverUrl,
CreatedAt: createdAt,
}
videos = append(videos, video)
}
}
return videos, nil
}

func (s *VideoService) GetVideoByIds(videoIds []int64) ([]*Video, error) {
db := s.dbInstance()

videos := make([]*Video, 0)
if err := db.Where("id IN ?", videoIds).Find(&videos).Error; err != nil {
return nil, err
rdb := s.redisClient()

videos := make([]*Video, 0, len(videoIds))
for _, videoId := range videoIds {
videoData, err := rdb.HGetAll(fmt.Sprintf("video:%d", videoId)).Result()
if err != nil {
return nil, err
} else if len(videoData) == 0 {
return nil, fmt.Errorf("video not found: %d", videoId)
}

// 解析videoData
userId, _ := strconv.ParseInt(videoData["UserId"], 10, 64)
title := videoData["Title"]
playUrl := videoData["PlayUrl"]
coverUrl := videoData["CoverUrl"]
createdAtStr := videoData["CreatedAt"]
createdAt, err := time.Parse(time.RFC3339, createdAtStr)
if err != nil {
return nil, err
}

video := &Video{
Id: videoId,
UserId: userId,
Title: title,
PlayUrl: playUrl,
CoverUrl: coverUrl,
CreatedAt: createdAt,
}
videos = append(videos, video)
}

return videos, nil
Expand All @@ -73,7 +152,7 @@ func (s *VideoService) GetFeed(latestTime int64) ([]*Video, error) {
if latestTime == 0 {
timeValue = time.Now()
} else {
timeValue = time.Unix(latestTime / time.Microsecond.Nanoseconds(), 0)
timeValue = time.Unix(latestTime/time.Microsecond.Nanoseconds(), 0)
}

if err := db.Where("created_at < ?", timeValue).Order("created_at desc").Limit(30).Find(&videos).Error; err != nil {
Expand Down
Loading

0 comments on commit 18e9a02

Please sign in to comment.