基本思路:定义一个chan,chan大小为需要限制的qps大小,go一个协程启动tick,每1000/qps时间在tick中写入数值,启动另一个协程,读取chan中的值,如果读取到chan中有值,则向下层接口发送请求。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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 令牌桶算法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/peng825223208/article/details/105599493