Files
2026-10-26 16:28:14 +08:00

59 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package ipstat
import (
"context"
"time"
"videoweb/pub/common/enum/redisconst"
"videoweb/pub/common/log"
"videoweb/pub/common/utils"
"videoweb/pub/models/ipdailystatmod"
"videoweb/pub/pubdef"
"videoweb/pub/redis"
)
const syncInterval = 5 * time.Minute
// StartSync 启动后台协程,每隔 syncInterval 将当日和昨日的 Redis IP SET
// 数量同步写入 MongoDB(ip_daily_stat),供 web 端查询。
func StartSync() {
go func() {
// 启动时立即同步一次
syncOnce()
ticker := time.NewTicker(syncInterval)
defer ticker.Stop()
for range ticker.C {
syncOnce()
}
}()
}
func syncOnce() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
now := time.Now().In(utils.LocBJ)
appId := int64(pubdef.AppId)
for _, offset := range []int{0, -1} {
date := now.AddDate(0, 0, offset).Format("20060102")
key := redisconst.IpStatKey(appId, date)
count, err := redis.SCard(key)
if err != nil {
log.Warn("ipstat sync: SCard failed",
log.Any("date", date), log.E(err))
continue
}
// 今日 Redis 为 0 时不覆盖 MongoDB,避免 key 丢失把已有数据写成 0。
if offset == 0 && count == 0 {
continue
}
if err := ipdailystatmod.UpsertCount(ctx, appId, date, count); err != nil {
log.Warn("ipstat sync: UpsertCount failed",
log.Any("appId", appId), log.Any("date", date), log.E(err))
}
}
}