59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package service
|
|
|
|
import (
|
|
"Blog/internal/client"
|
|
"Blog/internal/consts"
|
|
"Blog/internal/repository"
|
|
"context"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var ViewRecordService *viewRecordService = newViewRecordService()
|
|
|
|
type viewRecordService struct {
|
|
}
|
|
|
|
func initViewRecordData() {
|
|
type viewRecord struct {
|
|
RelId string
|
|
Counts int
|
|
}
|
|
var slices []viewRecord
|
|
repository.ViewRecordRepository.Table(consts.TABLE_BLOG_VIEW_RECORD).Select("rel_id ,count(1) counts").Group("rel_id").Find(&slices)
|
|
logrus.Info("点击量初始化数据加载量:", len(slices))
|
|
for _, val := range slices {
|
|
client.RedisClient.HSet(context.Background(), consts.REDIS_BLOG_VIEW_RECORD, map[string]any{val.RelId: val.Counts})
|
|
}
|
|
}
|
|
|
|
func newViewRecordService() *viewRecordService {
|
|
go initViewRecordData()
|
|
|
|
return &viewRecordService{}
|
|
}
|
|
|
|
func (*viewRecordService) GetRecord(id string) int64 {
|
|
var count int64 = 0
|
|
ctx := context.Background()
|
|
// exists := client.RedisClient.Exists(ctx, consts.REDIS_BLOG_VIEW_RECORD).Val()
|
|
exists := client.RedisClient.HExists(ctx, consts.REDIS_BLOG_VIEW_RECORD, id).Val()
|
|
if exists {
|
|
i, err := client.RedisClient.HGet(ctx, consts.REDIS_BLOG_VIEW_RECORD, id).Int64()
|
|
if err != nil {
|
|
return i
|
|
}
|
|
|
|
}
|
|
|
|
err := repository.ViewRecordRepository.Table(consts.TABLE_BLOG_VIEW_RECORD).Where("rel_id = ?", id).Count(&count).Error
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
err = client.RedisClient.HIncrBy(ctx, consts.REDIS_BLOG_VIEW_RECORD, id, count).Err()
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return count
|
|
}
|