feat(flow): 自 go-hua 迁入流量统计器
- 并发安全收发字节数累计(Add/Get/Reset), 附测试、例程与 README
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
// Package flow 提供并发安全的流量统计(只统计、不限制),常配合 conn 包使用。
|
||||
package flow
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// 统计流量 不限制流量
|
||||
type Flow struct {
|
||||
SendFlow int64 `json:"sendFlow"`
|
||||
RecvFlow int64 `json:"recvFlow"`
|
||||
FlowLimit int64 `json:"flowLimit"`
|
||||
}
|
||||
|
||||
// Add 累计发送/接收字节数
|
||||
func (f *Flow) Add(send, recv int64) {
|
||||
atomic.AddInt64(&f.SendFlow, send)
|
||||
atomic.AddInt64(&f.RecvFlow, recv)
|
||||
}
|
||||
|
||||
// Reset 取出并清零收发流量,返回清零前的值(用于周期性上报)
|
||||
func (f *Flow) Reset() (int64, int64) {
|
||||
send := atomic.SwapInt64(&f.SendFlow, 0)
|
||||
recv := atomic.SwapInt64(&f.RecvFlow, 0)
|
||||
return send, recv
|
||||
}
|
||||
|
||||
// Get 读取当前收发流量(不清零)
|
||||
func (f *Flow) Get() (int64, int64) {
|
||||
send := atomic.LoadInt64(&f.SendFlow)
|
||||
recv := atomic.LoadInt64(&f.RecvFlow)
|
||||
return send, recv
|
||||
}
|
||||
Reference in New Issue
Block a user