github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/requester/downloader/resetcontroler.go (about) 1 package downloader 2 3 import ( 4 "github.com/iikira/iikira-go-utils/utils/expires" 5 "sync" 6 "time" 7 ) 8 9 // ResetController 网络连接控制器 10 type ResetController struct { 11 mu sync.Mutex 12 currentTime time.Time 13 maxResetNum int 14 resetEntity map[expires.Expires]struct{} 15 } 16 17 // NewResetController 初始化*ResetController 18 func NewResetController(maxResetNum int) *ResetController { 19 return &ResetController{ 20 currentTime: time.Now(), 21 maxResetNum: maxResetNum, 22 resetEntity: map[expires.Expires]struct{}{}, 23 } 24 } 25 26 func (rc *ResetController) update() { 27 for k := range rc.resetEntity { 28 if k.IsExpires() { 29 delete(rc.resetEntity, k) 30 } 31 } 32 } 33 34 // AddResetNum 增加连接 35 func (rc *ResetController) AddResetNum() { 36 rc.mu.Lock() 37 defer rc.mu.Unlock() 38 rc.update() 39 rc.resetEntity[expires.NewExpires(9*time.Second)] = struct{}{} 40 } 41 42 // CanReset 是否可以建立连接 43 func (rc *ResetController) CanReset() bool { 44 rc.mu.Lock() 45 defer rc.mu.Unlock() 46 rc.update() 47 return len(rc.resetEntity) < rc.maxResetNum 48 }