Golang Simple Token Bucket Algorithm Implementation Code

 

This article mainly introduces the implementation code of golang simple token bucket algorithm. The article introduces the sample code in great detail. It has a certain reference learning value for everyone's study or work. Friends who need it, follow the editor to learn together.

Basic idea: define a chan, the size of the chan is the qps size that needs to be limited, go a coroutine to start tick, write the value in the tick every 1000/qps, start another coroutine, read the value in the chan, if read If there is a value in chan, send a request to the lower interface.

code show as below:

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)

    }

}

So far, this article about the implementation code of golang's simple token bucket algorithm has been introduced here, and I hope it can help you.

Reposted from: Micro reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131830456