go语言实现令牌桶算法

package main

import (
    "fmt"
    "time"
)

var (
    lastRequestTime int64 = time.Now().Unix()
    tokenSurplus    int64 = 0
    qps             int64 = 5
)

func getMin(a, b int64) int64 {
    if a > b {
        return b
    }
    return a
}

func getToken() bool {
    now := time.Now().Unix()
    temp := (now-lastRequestTime)*qps + tokenSurplus
    tokenNow := getMin(temp, qps)
    if tokenNow > 0 {
        lastRequestTime = now
        tokenSurplus--
        return true
    }
    return false
}

func main() {
    fmt.Println(time.Now().Unix())
}

你可能感兴趣的:(golang,令牌桶)