func FW(max int,duration time.Duration){
//定义一个channel ,进行初始化
contain := make(chan bool , max)
for i := 0 ; i max ; i ++{
contain - true//写入channel
}
go func() {//开启一个线程
for {
contain - true
time.Sleep(duration)
}
}()
for - contain {//如果上一个线程写入一个true,就会运行这个代码块
fmt.Println("helllo world")
}
}
定义一个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)
}
}