51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package async
|
|
|
|
import (
|
|
"blog/internal/consts"
|
|
"blog/third_party/database"
|
|
"context"
|
|
"log"
|
|
"math"
|
|
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var viewRecordChannel chan ViewRecord
|
|
|
|
type ViewRecord struct {
|
|
Id string `json:"id"`
|
|
ViewTime int64 `json:"viewTime"`
|
|
IpAddr string `json:"ipAddr"`
|
|
RelId string `json:"relId"`
|
|
Title string `json:"title" gorm:"-"`
|
|
}
|
|
|
|
func init() {
|
|
f := math.Pow(2, 5)
|
|
viewRecordChannel = make(chan ViewRecord, int(f))
|
|
go func() {
|
|
|
|
ctx := context.Background()
|
|
for record := range viewRecordChannel {
|
|
log.Println("IP:", record.IpAddr, "点击了:", record.Title)
|
|
relId := record.RelId
|
|
record.Id = uuid.NewString()
|
|
database.WGorm(func(tx *gorm.DB) error {
|
|
err := tx.Table("blog_view_record").Create(&record).Error
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err2 := database.RedisTemplate.HIncrBy(ctx, consts.REDIS_BLOG_VIEW_RECORD, relId, 1).Err()
|
|
return err2
|
|
})
|
|
// database.WGormUnlock()
|
|
}
|
|
|
|
}()
|
|
}
|
|
|
|
func PublishViewRecord(record ViewRecord) {
|
|
viewRecordChannel <- record
|
|
}
|