This commit is contained in:
ehlxr 2019-11-25 14:12:08 +08:00
parent 0b4c02be64
commit 4718b4ebd5
3 changed files with 27 additions and 38 deletions

View File

@ -74,8 +74,6 @@ func tailFile() {
if ok, _ := regexp.Match(pkg.Opts.KeyWord, []byte(text)); ok { if ok, _ := regexp.Match(pkg.Opts.KeyWord, []byte(text)); ok {
if limiter.IsAvailable() { if limiter.IsAvailable() {
limiter.Increase()
sendMsg(line.Text) sendMsg(line.Text)
} else { } else {
log.Error("dingTalk 1 m allow send 20 msg. msg %v discarded.", log.Error("dingTalk 1 m allow send 20 msg. msg %v discarded.",

View File

@ -3,47 +3,40 @@ package pkg
import ( import (
"sync" "sync"
"time" "time"
log "unknwon.dev/clog/v2"
) )
type LimiterServer struct { type LimiterServer struct {
Interval time.Duration interval time.Duration
MaxCount int maxCount int
Lock sync.Mutex sync.Mutex
ReqCount int reqCount int
startTime time.Time
} }
func NewLimiterServer(interval time.Duration, maxCount int) *LimiterServer { func NewLimiterServer(i time.Duration, c int) *LimiterServer {
limiter := &LimiterServer{ return &LimiterServer{
Interval: interval, interval: i,
MaxCount: maxCount, maxCount: c,
} }
go func() {
ticker := time.NewTicker(interval)
for {
<-ticker.C
limiter.Lock.Lock()
log.Info("Reset LimiterServer Count...")
limiter.ReqCount = 0
limiter.Lock.Unlock()
}
}()
return limiter
}
func (limiter *LimiterServer) Increase() {
limiter.Lock.Lock()
defer limiter.Lock.Unlock()
limiter.ReqCount += 1
} }
func (limiter *LimiterServer) IsAvailable() bool { func (limiter *LimiterServer) IsAvailable() bool {
limiter.Lock.Lock() limiter.Lock()
defer limiter.Lock.Unlock() defer limiter.Unlock()
return limiter.ReqCount < limiter.MaxCount if limiter.startTime.IsZero() ||
limiter.startTime.Add(limiter.interval).Before(time.Now()) {
limiter.reqCount = 1
limiter.startTime = time.Now()
return true
}
if limiter.reqCount < limiter.maxCount {
limiter.reqCount += 1
return true
}
return false
} }

View File

@ -10,9 +10,7 @@ func TestLimiter(t *testing.T) {
for { for {
if limiter.IsAvailable() { if limiter.IsAvailable() {
limiter.Increase() t.Log("hello...", limiter.reqCount)
t.Log("hello...", limiter.ReqCount)
} else { } else {
return return
} }