// 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. 和菜鸟一起学linux之DBUS基础学习记录

    D-Bus三层架构 D-Bus是一个为应用程序间通信的消息总线系统, 用于进程之间的通信.它是个3层架构的IPC 系统,包括: 1.函数库libdbus ,用于两个应用程序互相联系和交互消息. 2.一 ...

  2. vue学习:props,scope,slot,ref,is,slot,sync等知识点

    1.ref :为子组件指定一个索引 ID,给元素或者组件注册引用信息.refs是一个对象,包含所有的ref组件. <div id="parent"> <user- ...

  3. 经典栈溢出之MS060-040漏洞分析

    找了好久才找到Win 2000 NetApi32.dll样本,下面我对这个经典栈溢出进行一下分析,使用IDA打开NetApi32.dll,问题函数:NetpwPathCanonucalize.实验环境 ...

  4. lintcode 在O(1)时间复杂度删除链表节点

    题目要求 给定一个单链表中的一个等待被删除的节点(非表头或表尾).请在在O(1)时间复杂度删除该链表节点. 样例 Linked list is 1->2->3->4, and giv ...

  5. 关于引用(python中的伪指针)的理解

    # 总结:个人理解,引用不可变的的变量时,随着改变会指向新的地址 # 引用可变的变量时,位置不会随着变量改变而改变 a = 1 b = a print(b) a = 2 # 指向了新的内存地址 pri ...

  6. 【转】IE浏览器快捷键大全

    一般快捷键F11打开/关闭全屏模式 TAB循环的选择地址栏,刷新键和当前标签页 CTRL+F在当前标签页查询字或短语 CTRL+N为当前标签页打开一个新窗口 CTRL+P打印当前标签页 CTRL+A选 ...

  7. django相关网站

    记录django的学习笔记:http://www.cnblogs.com/qwj-sysu/tag/django/ uwsgi的文档:http://uwsgi-docs.readthedocs.io/ ...

  8. 1 Numpy-科学计算

    在Python中,使用list可以保存一组值,可以作为数组使用,但是比较浪费内存和时间.类似的array模块,不支持多维,也没有各种函数运算,因此也极其不方便. 为解决这一问题,Python提供了Nu ...

  9. SSH项目的pom.xml文件

    <!-- 属性 --> <properties> <spring.version>4.2.4.RELEASE</spring.version> < ...

  10. python_函数设计

    >>> def check_permission(func): def wrapper(*args,**kwargs): if kwargs.get('username')!='ad ...