简单实现令牌桶,复制即可用
package main
import (
"fmt"
"log"
"time"
)
var startTime = time.Now()
func main() {
bucket()
}
//令牌桶案例
func bucket() {
quantum := int64(1)
rate := float64(2)
capacity := int64(2)
count := int64(1)
fillInterval := time.Duration(1e9 * float64(quantum) / rate)
fmt.Printf("fillInterval : %d \n", fillInterval)
availableTokens := int64(2)
var lastTick int64
t := time.NewTicker(400 * time.Millisecond)
for e := range t.C {
//当前时间与服务启动时间的差值,除以时间间隔 -> 算出数量
tick := int64(time.Now().Sub(startTime) / fillInterval)
if availableTokens >= capacity {
fmt.Printf("ok use [%d]\n", availableTokens)
} else {
//两个相减,算出真正的可用数量
availableTokens += (tick - lastTick) * quantum
fmt.Printf("tick - lastTick : %d\n", availableTokens)
if availableTokens > capacity {
availableTokens = capacity
}
lastTick = tick
}
if availableTokens <= 0 {
log.Println("no availableTokens")
} else {
if count > availableTokens {
count = availableTokens
}
availableTokens -= count
fmt.Printf("[%+v], availableTokens has [%d]\n", e, availableTokens)
}
}
}
网友评论