update at 2019-11-26 13:50:08 by ehlxr

This commit is contained in:
ehlxr 2019-11-26 13:50:08 +08:00
parent 4718b4ebd5
commit e6869549e5
2 changed files with 24 additions and 12 deletions

View File

@ -9,32 +9,30 @@ type LimiterServer struct {
interval time.Duration interval time.Duration
maxCount int maxCount int
sync.Mutex sync.Mutex
reqCount int reqCount int
startTime time.Time time time.Time
} }
func NewLimiterServer(i time.Duration, c int) *LimiterServer { func NewLimiterServer(interval time.Duration, maxCount int) *LimiterServer {
return &LimiterServer{ return &LimiterServer{
interval: i, interval: interval,
maxCount: c, maxCount: maxCount,
} }
} }
func (limiter *LimiterServer) IsAvailable() bool { func (limiter *LimiterServer) IsAvailable() bool {
limiter.Lock() limiter.Lock()
defer limiter.Unlock() defer limiter.Unlock()
now := time.Now()
if limiter.startTime.IsZero() || if limiter.time.IsZero() ||
limiter.startTime.Add(limiter.interval).Before(time.Now()) { limiter.time.Add(limiter.interval).Before(now) {
limiter.reqCount = 1 limiter.reqCount = 0
limiter.startTime = time.Now()
return true
} }
if limiter.reqCount < limiter.maxCount { if limiter.reqCount < limiter.maxCount {
limiter.reqCount += 1 limiter.reqCount += 1
limiter.time = now
return true return true
} }

View File

@ -1,6 +1,7 @@
package pkg package pkg
import ( import (
"fmt"
"testing" "testing"
"time" "time"
) )
@ -16,3 +17,16 @@ func TestLimiter(t *testing.T) {
} }
} }
} }
func TestLimiter2(t *testing.T) {
limiter := NewLimiterServer(10*time.Second, 10)
for i := 0; i < 20; i++ {
if limiter.IsAvailable() {
fmt.Println("hello...", limiter.reqCount)
} else {
fmt.Println("limited")
}
time.Sleep(1 * time.Second)
}
}