From 5da09af54929a51d105a8835d533f5af9862b7aa Mon Sep 17 00:00:00 2001 From: qydysky Date: Mon, 12 Apr 2021 15:39:27 +0800 Subject: [PATCH] add TK func for limit --- limit/Limit.go | 16 ++++++++++++---- limit/Limit_test.go | 9 +++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/limit/Limit.go b/limit/Limit.go index 6489be7..410a2c8 100644 --- a/limit/Limit.go +++ b/limit/Limit.go @@ -8,7 +8,7 @@ type Limit struct { maxNum_in_period int ms_in_period int ms_to_timeout int - channl chan struct{} + bucket chan struct{} } // create a Limit Object @@ -18,26 +18,34 @@ func New(maxNum_in_period,ms_in_period,ms_to_timeout int) (*Limit) { maxNum_in_period:maxNum_in_period, ms_in_period:ms_in_period, ms_to_timeout:ms_to_timeout, - channl:make(chan struct{},maxNum_in_period), + bucket:make(chan struct{},maxNum_in_period), } go func(object *Limit){ for object.maxNum_in_period > 0 { for i:=1;i<=object.maxNum_in_period;i++{ - object.channl <- struct{}{} + object.bucket <- struct{}{} } time.Sleep(time.Duration(object.ms_in_period)*time.Millisecond) } }(&object) + //make sure the bucket is full + for object.TK() != maxNum_in_period {} + return &object } // the func will return true if the request(call TO()) is up to limit and return false if not func (l *Limit) TO() bool { select { - case <-l.channl :; + case <-l.bucket :; case <-time.After(time.Duration(l.ms_to_timeout)*time.Millisecond):return true; } return false +} + +// return the token number of bucket +func (l *Limit) TK() int { + return len(l.bucket) } \ No newline at end of file diff --git a/limit/Limit_test.go b/limit/Limit_test.go index be2730f..7441449 100644 --- a/limit/Limit_test.go +++ b/limit/Limit_test.go @@ -51,4 +51,13 @@ func Test_4(t *testing.T){ time.Sleep(time.Millisecond) } t.Log(pass) +} + +func Test_5(t *testing.T){ + l := New(100,5000,0) + for i:=0;i<50;i+=1{ + l.TO() + time.Sleep(time.Millisecond) + } + if l.TK() != 50 {t.Error(`5`,l.TK())} } \ No newline at end of file -- 2.39.2