func FW(max int,duration time.Duration){
//定義一個(gè)channel ,進(jìn)行初始化
contain := make(chan bool , max)
for i := 0 ; i max ; i ++{
contain - true//寫入channel
}
go func() {//開啟一個(gè)線程
for {
contain - true
time.Sleep(duration)
}
}()
for - contain {//如果上一個(gè)線程寫入一個(gè)true,就會運(yùn)行這個(gè)代碼塊
fmt.Println("helllo world")
}
}
定義一個(gè)chan,chan大小為需要限制的qps大小,go一個(gè)協(xié)程啟動tick,每1000/qps時(shí)間在tick中寫入數(shù)值,啟動另一個(gè)協(xié)程,讀取chan中的值,如果讀取到chan中有值,則向下層接口發(fā)送請求。
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 {
//收客戶請求,發(fā)送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)
}
}