// 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. obj-c编程13:归档

    这篇归档内容的博文也挺有趣的,笨猫对好玩的东西一向感兴趣啊!如果用过ruby就会知道,obj-c里的归档类似于ruby中的序列化概念,不过从语法的简洁度来说,我只能又一次呵呵了. 下面大家将会看到2种 ...

  2. Java IO学习--(三)通道

    Java IO中的管道为运行在同一个JVM中的两个线程提供了通信的能力.所以管道也可以作为数据源以及目标媒介. 你不能利用管道与不同的JVM中的线程通信(不同的进程).在概念上,Java的管道不同于U ...

  3. NewLife.Net——开始网络编程

    网络编程的重要性就不说了,先上源码:https://github.com/nnhy/NewLife.Net.Tests 一个服务端,就是监听一些端口,接收客户端连接和数据,进行处理,然后响应. /// ...

  4. codechef Killing Monsters

    题目大意:大厨正在玩一个打怪兽的小游戏.游戏中初始时有 n 只怪兽排成一排,从左到右编号为 0 ∼ n − 1.第 i 只怪兽的初始血量为 hi,当怪兽的血量小于等于 0 时,这只怪兽就挂了. 大厨要 ...

  5. AngularJS之备忘与诀窍

    译自:<angularjs> 备忘与诀窍 目前为止,之前的章节已经覆盖了Angular所有功能结构中的大多数,包括指令,服务,控制器,资源以及其它内容.但是我们知道有时候仅仅阅读是不够的. ...

  6. Android Gradle使用总结

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/77678577 本文出自[赵彦军的博客] 其他 Groovy 使用完全解析 http ...

  7. Java 代码重用:操作与上下文重用

    目录 操作重用 参数化操作 上下文重用 上下文作为模板方法 结束语 我几乎不需要讨论为什么重用代码是有利的.代码重用(通常)会导致更快的开发与更少的 BUG.一旦一段代码被封装和重用,那么检查程序是否 ...

  8. mongodb的安装使用,window和centos环境

    官网:https://www.mongodb.org/downloads 版本:最终稳定版 (mongodb-win32-x86_64-2008plus-ssl-3.2.6-signed.msi 绿色 ...

  9. 震惊!外部类可以访问内部类private变量

    在讲Singleton时我举例时用过这样一段代码: public class SingletonDemo { private static class SingletonHolder{ private ...

  10. 浅谈C++ STL中的优先队列(priority_queue)

    从我以前的博文能看出来,我是一个队列爱好者,很多并不是一定需要用队列实现的算法我也会采用队列实现,主要是由于队列和人的直觉思维的一致性导致的. 今天讲一讲优先队列(priority_queue),实际 ...