SoFunction
Updated on 2025-03-01

Golang simulates the flow restriction method of token buckets for access

Use channel to simulate token buckets to limit access flow

func FW(max int,duration ){
//Define a channel and perform initialization	contain := make(chan bool , max)
	for i := 0 ; i < max ; i ++{
		contain <- true//Write to channel	}
	go func() {//Open a thread		for {
			contain <- true
			(duration)
		}
	}()
	for <- contain {//If the previous thread writes a true, this code block will be run		("helllo world")
	}
}

Supplement: Golang simple token bucket algorithm implementation

Basic ideas:

Define a chan, the size of the chan is the qps size that needs to be limited. Go to a coroutine starts the tick, writes a value in the tick every 1000/qps time, starts another coroutine, reads the value in the chan, and sends a request to the down-level interface if there is a value in the chan.

The code is as follows:

package main
import (
    "fmt"
    "time"
    "httpclient"
)
var LEN int = 10
func tickStoreCh(arrlen int, ch chan int) {
    len := 1000/arrlen
    (len)
    tickTime := ((len)*)
    var i int
    for {
        (len)
        i++
        <-
        ch<- i
    }
}
func OrganReq(org string, qps int) {
    ch := make(chan int, qps)
    go tickStoreCh(qps, ch)
    (1000*)
    for {
        //Check customer requests and send http requests to RE        client := ((1000)*, (2000)*)
        header := make(map[string]string)
        header["Content-Type"] = "application/json;charset=utf-8"
        code, err := ("http://127.0.0.1:19988", header, "llltest")
        value := <- ch
        (code, value, err, "lenchan:", len(ch))
        //()
    }
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.