51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package async
|
|
|
|
import (
|
|
"Blog/internal/client"
|
|
"Blog/internal/consts"
|
|
"Blog/internal/model"
|
|
"Blog/internal/repository"
|
|
"context"
|
|
"math"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/sirupsen/logrus"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var viewRecordChannel chan model.ViewRecord
|
|
|
|
func init() {
|
|
f := math.Pow(2, 5)
|
|
viewRecordChannel = make(chan model.ViewRecord, int(f))
|
|
go func() {
|
|
|
|
ctx := context.Background()
|
|
for record := range viewRecordChannel {
|
|
logrus.Info("IP:", record.IpAddr, "点击了:", record.Title)
|
|
relId := record.RelId
|
|
record.Id = uuid.NewString()
|
|
err := repository.ViewRecordRep().WGorm(func(tx *gorm.DB) error {
|
|
err := tx.Table(consts.TABLE_BLOG_VIEW_RECORD).Create(&record).Error
|
|
return err
|
|
})
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
logrus.Error("流量记录保存失败")
|
|
}
|
|
|
|
err = client.RedisClient().HIncrBy(ctx, consts.REDIS_BLOG_VIEW_RECORD, relId, 1).Err()
|
|
if err != nil {
|
|
logrus.Error(err)
|
|
logrus.Error("流量记录写入Redis失败:", record.Title)
|
|
}
|
|
// database.WGormUnlock()
|
|
}
|
|
|
|
}()
|
|
}
|
|
|
|
func PublishViewRecord(record model.ViewRecord) {
|
|
viewRecordChannel <- record
|
|
}
|