rate limiting _ golang

jackkiexu · · 2802 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Rate limiting is an import mechanism for controlling resource utilzation and maintaining quality of service. Go elegantly supports rate with goroutines, channels, and tickers.

package main

import (
    "fmt"
    "time"
)

func main() {

    requests := make(chan int, 5)
    for i := 1; i <= 5; i++ {
        requests <- i
    }
    close(requests)

    limiter := time.Tick(time.Millisecond * 200)

    for req := range requests {
        <-limiter
        fmt.Println("request", req, time.Now())
    }

    burstyLimiter := make(chan time.Time, 3)

    for i := 3; i < 3; i++ {
        burstyLimiter <- time.Now()
    }

    go func() {
        for t := range time.Tick(time.Millisecond * 200) {
            burstyLimiter <- t
        }
    }()

    burstyRequests := make(chan int, 5)
    for i := 1; i <= 5; i++ {
        burstyRequests <- i
    }

    close(burstyRequests)
    for req := range burstyRequests {
        <-burstyLimiter
        fmt.Println("request", req, time.Now())
    }
}
request 1 2015-03-19 13:28:50.374160158 +0800 CST
request 2 2015-03-19 13:28:50.574201973 +0800 CST
request 3 2015-03-19 13:28:50.774188326 +0800 CST
request 4 2015-03-19 13:28:50.973780019 +0800 CST
request 5 2015-03-19 13:28:51.174145507 +0800 CST
request 1 2015-03-19 13:28:51.374323823 +0800 CST
request 2 2015-03-19 13:28:51.574328349 +0800 CST
request 3 2015-03-19 13:28:51.774329018 +0800 CST
request 4 2015-03-19 13:28:51.974462542 +0800 CST
request 5 2015-03-19 13:28:52.174320544 +0800 CST

总结 : 

  1 : .....


有疑问加站长微信联系(非本文作者)

本文来自:博客园

感谢作者:jackkiexu

查看原文:rate limiting _ golang

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2802 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传