增加网站每日独立IP统计

This commit is contained in:
刘祥超
2024-04-12 20:12:09 +08:00
parent 62f8ed63be
commit fe069762bb
5 changed files with 442 additions and 12 deletions

View File

@@ -76,12 +76,15 @@ type BandwidthStatManager struct {
ticker *time.Ticker
locker sync.Mutex
cacheFile string
}
func NewBandwidthStatManager() *BandwidthStatManager {
return &BandwidthStatManager{
m: map[string]*BandwidthStat{},
ticker: time.NewTicker(1 * time.Minute), // 时间小于1分钟是为了更快速地上传结果
m: map[string]*BandwidthStat{},
ticker: time.NewTicker(1 * time.Minute), // 时间小于1分钟是为了更快速地上传结果
cacheFile: Tea.Root + "/data/stat_bandwidth.cache",
}
}
@@ -130,6 +133,8 @@ func (this *BandwidthStatManager) Loop() error {
this.pbStats = nil
}
var ipStatMap = SharedDAUManager.ReadStatMap()
this.locker.Lock()
for key, stat := range this.m {
if stat.Day < day || stat.TimeAt < currentTime {
@@ -142,6 +147,8 @@ func (this *BandwidthStatManager) Loop() error {
stat.AttackBytes = stat.TotalBytes
}
var ipKey = "server_" + stat.Day + "_" + types.String(stat.ServerId)
pbStats = append(pbStats, &pb.ServerBandwidthStat{
Id: 0,
UserId: stat.UserId,
@@ -156,6 +163,7 @@ func (this *BandwidthStatManager) Loop() error {
CountCachedRequests: stat.CountCachedRequests,
CountAttackRequests: stat.CountAttackRequests,
CountWebsocketConnections: stat.CountWebsocketConnections,
CountIPs: ipStatMap[ipKey],
UserPlanId: stat.UserPlanId,
NodeRegionId: regionId,
})
@@ -284,8 +292,8 @@ func (this *BandwidthStatManager) Save() error {
return err
}
_ = os.Remove(this.cacheFile())
return os.WriteFile(this.cacheFile(), data, 0666)
_ = os.Remove(this.cacheFile)
return os.WriteFile(this.cacheFile, data, 0666)
}
// Cancel 取消上传
@@ -295,7 +303,7 @@ func (this *BandwidthStatManager) Cancel() {
// 从本地缓存文件中恢复数据
func (this *BandwidthStatManager) recover() {
cacheData, err := os.ReadFile(this.cacheFile())
cacheData, err := os.ReadFile(this.cacheFile)
if err == nil {
var m = map[string]*BandwidthStat{}
err = json.Unmarshal(cacheData, &m)
@@ -317,12 +325,6 @@ func (this *BandwidthStatManager) recover() {
}
}
}
_ = os.Remove(this.cacheFile())
_ = os.Remove(this.cacheFile)
}
}
// 获取缓存文件
// 不能在init()中初始化,避免无法获得正确的路径
func (this *BandwidthStatManager) cacheFile() string {
return Tea.Root + "/data/bandwidth.dat"
}