2023-07-27 21:13:11 -04:00
|
|
|
package counter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
)
|
|
|
|
|
|
|
|
type TrafficCounter struct {
|
2024-07-28 00:54:47 -04:00
|
|
|
counters sync.Map
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
type TrafficStorage struct {
|
|
|
|
UpCounter atomic.Int64
|
|
|
|
DownCounter atomic.Int64
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTrafficCounter() *TrafficCounter {
|
2024-07-28 00:54:47 -04:00
|
|
|
return &TrafficCounter{}
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) GetCounter(id string) *TrafficStorage {
|
2024-07-28 00:54:47 -04:00
|
|
|
if cts, ok := c.counters.Load(id); ok {
|
|
|
|
return cts.(*TrafficStorage)
|
|
|
|
}
|
|
|
|
newStorage := &TrafficStorage{}
|
|
|
|
if cts, loaded := c.counters.LoadOrStore(id, newStorage); loaded {
|
|
|
|
return cts.(*TrafficStorage)
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
2024-07-28 00:54:47 -04:00
|
|
|
return newStorage
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) GetUpCount(id string) int64 {
|
2024-07-28 00:54:47 -04:00
|
|
|
if cts, ok := c.counters.Load(id); ok {
|
|
|
|
return cts.(*TrafficStorage).UpCounter.Load()
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) GetDownCount(id string) int64 {
|
2024-07-28 00:54:47 -04:00
|
|
|
if cts, ok := c.counters.Load(id); ok {
|
|
|
|
return cts.(*TrafficStorage).DownCounter.Load()
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2023-07-29 06:47:47 -04:00
|
|
|
func (c *TrafficCounter) Len() int {
|
2024-07-28 00:54:47 -04:00
|
|
|
length := 0
|
|
|
|
c.counters.Range(func(_, _ interface{}) bool {
|
|
|
|
length++
|
|
|
|
return true
|
|
|
|
})
|
|
|
|
return length
|
2023-07-29 06:47:47 -04:00
|
|
|
}
|
|
|
|
|
2023-07-27 21:13:11 -04:00
|
|
|
func (c *TrafficCounter) Reset(id string) {
|
2024-07-28 00:54:47 -04:00
|
|
|
if cts, ok := c.counters.Load(id); ok {
|
|
|
|
cts.(*TrafficStorage).UpCounter.Store(0)
|
|
|
|
cts.(*TrafficStorage).DownCounter.Store(0)
|
|
|
|
}
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) Delete(id string) {
|
2024-07-28 00:54:47 -04:00
|
|
|
c.counters.Delete(id)
|
2023-07-27 21:13:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) Rx(id string, n int) {
|
|
|
|
cts := c.GetCounter(id)
|
|
|
|
cts.DownCounter.Add(int64(n))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *TrafficCounter) Tx(id string, n int) {
|
|
|
|
cts := c.GetCounter(id)
|
|
|
|
cts.UpCounter.Add(int64(n))
|
|
|
|
}
|