From 4718b4ebd534c0d0807de14d9a47c9b093014df1 Mon Sep 17 00:00:00 2001 From: ehlxr Date: Mon, 25 Nov 2019 14:12:08 +0800 Subject: [PATCH] init --- main.go | 2 -- pkg/limiter.go | 59 ++++++++++++++++++++------------------------- pkg/limiter_test.go | 4 +-- 3 files changed, 27 insertions(+), 38 deletions(-) diff --git a/main.go b/main.go index b67487f..78af73e 100644 --- a/main.go +++ b/main.go @@ -74,8 +74,6 @@ func tailFile() { if ok, _ := regexp.Match(pkg.Opts.KeyWord, []byte(text)); ok { if limiter.IsAvailable() { - limiter.Increase() - sendMsg(line.Text) } else { log.Error("dingTalk 1 m allow send 20 msg. msg %v discarded.", diff --git a/pkg/limiter.go b/pkg/limiter.go index 6c80958..e2912a7 100644 --- a/pkg/limiter.go +++ b/pkg/limiter.go @@ -3,47 +3,40 @@ package pkg import ( "sync" "time" - log "unknwon.dev/clog/v2" ) type LimiterServer struct { - Interval time.Duration - MaxCount int - Lock sync.Mutex - ReqCount int + interval time.Duration + maxCount int + sync.Mutex + reqCount int + startTime time.Time } -func NewLimiterServer(interval time.Duration, maxCount int) *LimiterServer { - limiter := &LimiterServer{ - Interval: interval, - MaxCount: maxCount, +func NewLimiterServer(i time.Duration, c int) *LimiterServer { + return &LimiterServer{ + interval: i, + 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 { - limiter.Lock.Lock() - defer limiter.Lock.Unlock() + limiter.Lock() + 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 } diff --git a/pkg/limiter_test.go b/pkg/limiter_test.go index 3da6542..1a8f368 100644 --- a/pkg/limiter_test.go +++ b/pkg/limiter_test.go @@ -10,9 +10,7 @@ func TestLimiter(t *testing.T) { for { if limiter.IsAvailable() { - limiter.Increase() - - t.Log("hello...", limiter.ReqCount) + t.Log("hello...", limiter.reqCount) } else { return }