基本思路:定义一个chan,chan大小为需要限制的qps大小,go一个协程启动tick,每1000/qps时间在tick中写入数值,启动另一个协程,读取chan中的值,如果读取到chan中有值,则向下层接口发送请求。
代码如下:
package main
import (
"fmt"
"time"
"httpclient"
)
var LEN int = 10
func tickStoreCh(arrlen int, ch chan int) {
len := 1000/arrlen
fmt.Println(len)
tickTime := time.NewTicker(time.Duration(len)*time.Millisecond)
var i int
for {
fmt.Println(len)
i++
<-tickTime.C
ch<- i
}
}
func OrganReq(org string, qps int) {
ch := make(chan int, qps)
go tickStoreCh(qps, ch)
time.Sleep(1000*time.Millisecond)
for {
//收客户请求,发送http请求给RE
client := httpclient.NewHttpClient(time.Duration(1000)*time.Millisecond, time.Duration(2000)*time.Millisecond)
header := make(map[string]string)
header["Content-Type"] = "application/json;charset=utf-8"
code, err := client.ResponseCode("http://127.0.0.1:19988", header, "llltest")
value := <- ch
fmt.Println(code, value, err, "lenchan:", len(ch))
//time.Sleep(time.Second)
}
}
到此这篇关于golang简易令牌桶算法实现代码的文章就介绍到这了,更多相关golang 令牌桶算法内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!