// The ratelimit package provides an efficient token bucket implementation
// that can be used to limit the rate of arbitrary things.
// See http://en.wikipedia.org/wiki/Token_bucket.
package ratelimit

import (
    "math"
    "strconv"
    "sync"
    "time"
)

// Bucket represents a token bucket that fills at a predetermined rate.
// Methods on Bucket may be called concurrently.
//令牌桶  结构体
type Bucket struct {
    startTime    time.Time  //开始时间
    capacity     int64    //令牌桶容量
    quantum      int64     //
    fillInterval time.Duration   //

    // The mutex guards the fields following it.
    mu sync.Mutex

    // avail holds the number of available tokens
    // in the bucket, as of availTick ticks from startTime.
    // It will be negative when there are consumers
    // waiting for tokens.
    avail     int64
    availTick int64
}

// NewBucket returns a new token bucket that fills at the
// rate of one token every fillInterval, up to the given
// maximum capacity. Both arguments must be
// positive. The bucket is initially full.
func NewBucket(fillInterval time.Duration, capacity int64) *Bucket {
    return NewBucketWithQuantum(fillInterval, capacity, 1)
}

// rateMargin specifes the allowed variance of actual
// rate from specified rate. 1% seems reasonable.
const rateMargin = 0.01

// NewBucketWithRate returns a token bucket that fills the bucket
// at the rate of rate tokens per second up to the given
// maximum capacity. Because of limited clock resolution,
// at high rates, the actual rate may be up to 1% different from the
// specified rate.
func NewBucketWithRate(rate float64, capacity int64) *Bucket {
    for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) {
        fillInterval := time.Duration(1e9 * float64(quantum) / rate)
        if fillInterval <= 0 {
            continue
        }
        tb := NewBucketWithQuantum(fillInterval, capacity, quantum)
        if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin {
            return tb
        }
    }
    panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, 'g', -1, 64))
}

// nextQuantum returns the next quantum to try after q.
// We grow the quantum exponentially, but slowly, so we
// get a good fit in the lower numbers.
func nextQuantum(q int64) int64 {
    q1 := q * 11 / 10
    if q1 == q {
        q1++
    }
    return q1
}

// NewBucketWithQuantum is similar to NewBucket, but allows
// the specification of the quantum size - quantum tokens
// are added every fillInterval.
func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket {
    if fillInterval <= 0 {
        panic("token bucket fill interval is not > 0")
    }
    if capacity <= 0 {
        panic("token bucket capacity is not > 0")
    }
    if quantum <= 0 {
        panic("token bucket quantum is not > 0")
    }
    return &Bucket{
        startTime:    time.Now(),
        capacity:     capacity,
        quantum:      quantum,
        avail:        capacity,
        fillInterval: fillInterval,
    }
}

// Wait takes count tokens from the bucket, waiting until they are
// available.
func (tb *Bucket) Wait(count int64) {
    if d := tb.Take(count); d > 0 {
        time.Sleep(d)
    }
}

// WaitMaxDuration is like Wait except that it will
// only take tokens from the bucket if it needs to wait
// for no greater than maxWait. It reports whether
// any tokens have been removed from the bucket
// If no tokens have been removed, it returns immediately.
func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool {
    d, ok := tb.TakeMaxDuration(count, maxWait)
    if d > 0 {
        time.Sleep(d)
    }
    return ok
}

const infinityDuration time.Duration = 0x7fffffffffffffff

// Take takes count tokens from the bucket without blocking. It returns
// the time that the caller should wait until the tokens are actually
// available.
//
// Note that if the request is irrevocable - there is no way to return
// tokens to the bucket once this method commits us to taking them.
func (tb *Bucket) Take(count int64) time.Duration {
    d, _ := tb.take(time.Now(), count, infinityDuration)
    return d
}

// TakeMaxDuration is like Take, except that
// it will only take tokens from the bucket if the wait
// time for the tokens is no greater than maxWait.
//
// If it would take longer than maxWait for the tokens
// to become available, it does nothing and reports false,
// otherwise it returns the time that the caller should
// wait until the tokens are actually available, and reports
// true.
func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) {
    return tb.take(time.Now(), count, maxWait)
}

// TakeAvailable takes up to count immediately available tokens from the
// bucket. It returns the number of tokens removed, or zero if there are
// no available tokens. It does not block.
func (tb *Bucket) TakeAvailable(count int64) int64 {
    return tb.takeAvailable(time.Now(), count)
}

// takeAvailable is the internal version of TakeAvailable - it takes the
// current time as an argument to enable easy testing.
func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 {
    if count <= 0 {
        return 0
    }
    tb.mu.Lock()
    defer tb.mu.Unlock()

    tb.adjust(now)
    if tb.avail <= 0 {
        return 0
    }
    if count > tb.avail {
        count = tb.avail
    }
    tb.avail -= count
    return count
}

// Available returns the number of available tokens. It will be negative
// when there are consumers waiting for tokens. Note that if this
// returns greater than zero, it does not guarantee that calls that take
// tokens from the buffer will succeed, as the number of available
// tokens could have changed in the meantime. This method is intended
// primarily for metrics reporting and debugging.
func (tb *Bucket) Available() int64 {
    return tb.available(time.Now())
}

// available is the internal version of available - it takes the current time as
// an argument to enable easy testing.
func (tb *Bucket) available(now time.Time) int64 {
    tb.mu.Lock()
    defer tb.mu.Unlock()
    tb.adjust(now)
    return tb.avail
}

// Capacity returns the capacity that the bucket was created with.
func (tb *Bucket) Capacity() int64 {
    return tb.capacity
}

// Rate returns the fill rate of the bucket, in tokens per second.
func (tb *Bucket) Rate() float64 {
    return 1e9 * float64(tb.quantum) / float64(tb.fillInterval)
}

// take is the internal version of Take - it takes the current time as
// an argument to enable easy testing.
func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) {
    if count <= 0 {
        return 0, true
    }
    tb.mu.Lock()
    defer tb.mu.Unlock()

    currentTick := tb.adjust(now)
    avail := tb.avail - count
    if avail >= 0 {
        tb.avail = avail
        return 0, true
    }
    // Round up the missing tokens to the nearest multiple
    // of quantum - the tokens won't be available until
    // that tick.
    endTick := currentTick + (-avail+tb.quantum-1)/tb.quantum
    endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval)
    waitTime := endTime.Sub(now)
    if waitTime > maxWait {
        return 0, false
    }
    tb.avail = avail
    return waitTime, true
}

// adjust adjusts the current bucket capacity based on the current time.
// It returns the current tick.
func (tb *Bucket) adjust(now time.Time) (currentTick int64) {
    currentTick = int64(now.Sub(tb.startTime) / tb.fillInterval)

    if tb.avail >= tb.capacity {
        return
    }
    tb.avail += (currentTick - tb.availTick) * tb.quantum
    if tb.avail > tb.capacity {
        tb.avail = tb.capacity
    }
    tb.availTick = currentTick
    return
}

ratelimit.go的更多相关文章

  1. spring cloud网关通过Zuul RateLimit 限流配置

    目录 引入依赖 配置信息 RateLimit源码简单分析 RateLimit详细的配置信息解读 在平常项目中为了防止一些没有token访问的API被大量无限的调用,需要对一些服务进行API限流.就好比 ...

  2. python ratelimit使用

    1.https://pypi.org/project/ratelimit/

  3. .NET服务治理之限流中间件-FireflySoft.RateLimit

    概述 FireflySoft.RateLimit自2021年1月发布第一个版本以来,经历了多次升级迭代,目前已经十分稳定,被很多开发者应用到了生产系统中,最新发布的版本是3.0.0. Github:h ...

  4. 【Knockout.js 学习体验之旅】(1)ko初体验

    前言 什么,你现在还在看knockout.js?这货都已经落后主流一千年了!赶紧去学Angular.React啊,再不赶紧的话,他们也要变out了哦.身旁的90后小伙伴,嘴里还塞着山东的狗不理大蒜包, ...

  5. 爬虫requests模块 2

    会话对象¶ 会话对象让你能够跨请求保持某些参数.它也会在同一个 Session 实例发出的所有请求之间保持 cookie, 期间使用 urllib3 的 connection pooling 功能.所 ...

  6. WebApiThrottle限流框架使用手册

    阅读目录: 介绍 基于IP全局限流 基于IP的端点限流 基于IP和客户端key的端点限流 IP和客户端key的白名单 IP和客户端key自定义限制频率 端点自定义限制频率 关于被拒请求的计数器 在we ...

  7. KnockoutJS 3.X API 第七章 其他技术(4) 速率限制

    注意:这个速率限制API是在Knockout 3.1.0中添加的. 通常,更改的observable立即通知其订户,以便依赖于observable的任何计算的observable或绑定都会同步更新. ...

  8. cisco-log

    每个日志消息被关联一个严重级别,用来分类消息的严重等级:数字越低,消息越严重.严重级别的范围从0(最高)到7(最低).  日志消息的严重级别,使用logging命令可以用数字或者名称来指定严重性.  ...

  9. haproxy para config

    .. from http://www.cnblogs.com/dkblog/archive/2012/03/13/2393321.html 常用配置选项: OPTION 选项: option http ...

随机推荐

  1. Course3-Python文件I/O

    1. 读取键盘输入 Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘.如下: 1). raw_input. raw_input([prompt]) 函数从标准输入读取一个行, ...

  2. aside元素

    aside元素用来表示当前页面或文章的附属信息部分,它可以包含与当前页面或主要内容相关的引用.侧边栏.广告.导航条,以及其他类似的有别于主要内容的部分. aside元素主要有以下两种使用方法: 1.包 ...

  3. Docker学习笔记【四】Docker 仓库

    访问仓库,仓库是集中从存放镜像的地方.类似Maven. Docker Hub 目前由Docker官方维护的一个公共仓库,其中包括15000的镜像. 注册 在 https://hub.docker.co ...

  4. MDCC2013会议笔记

    技术性的Topic听的不多,也没记多少东西. 下面这些是产品设计论坛的笔记: 互联网为实体行业带来:数据驱动,用户参与,快速验证想法 体验整合:线上与线下,产品与服务,运营与营销,用户和利益相关方体验 ...

  5. sql server数据字符串分割功能sql

    --分割字符串函数 create FUNCTION [dbo].[GetSplitStringValueInIndex] ( ), --要分割的字符串 ), --分隔符号 @index INT --取 ...

  6. 学习MySQL我们应该知道哪些东西?

    随笔:小编由于年前一直在找工作,而年后找到工作后又一直在忙工作,所以也很少有时间给大家写点什么,总的来说呢,回顾一下之前面试的几次经历,也曾小小的总结了一下自己的不足,发现自己虽然一直在原有的公司(外 ...

  7. kaggle入门项目:Titanic存亡预测(三)数据可视化与统计分析

    ---恢复内容开始--- 原kaggle比赛地址:https://www.kaggle.com/c/titanic 原kernel地址:A Data Science Framework: To Ach ...

  8. File,FileInfo,FileStream,StreamReader的区别与用法

    概括的说,File,FileInfo,FileStream是用于文件 I/O 的类,StreamReader是用于从流读取和写入流的类,使用之前都需using System.IO. 先定义一个TXT文 ...

  9. 深入理解.net - 3.类型Type

    说到类型,.NET技术是基于通用类型系统(CTS,Common Type System)的,而CTS又是构建于公共语言架构(CLI,Common Language Infrastructure)之上, ...

  10. Scrapy爬虫框架补充内容一(Linux环境)

    Scrapy爬虫框架结构及工作原理详解 scrapy框架的框架结构如下: 组件分析: ENGINE:(核心):处理整个框架的数据流,各个组件在其控制下协同工作 SCHEDULER(调度器):负责接收引 ...