🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ### 原子计数器 实例:go 实现原子计数器的限流 <details> <summary>main.go</summary> ``` package main import ( "fmt" "io" "net/http" "sync" "time" ) type RequestLimitService struct { Interval time.Duration MaxCount int Lock sync.Mutex ReqCount int } func NewRequestLimitService(interval time.Duration, maxCnt int) *RequestLimitService { reqLimit := &RequestLimitService{ Interval: interval, MaxCount: maxCnt, } go func() { ticker := time.NewTicker(interval) for { select { case <-ticker.C: reqLimit.Lock.Lock() fmt.Println("Reset Count...") reqLimit.ReqCount = 0 reqLimit.Lock.Unlock() } } }() return reqLimit } func (reqLimit *RequestLimitService) Increase() { reqLimit.Lock.Lock() defer reqLimit.Lock.Unlock() reqLimit.ReqCount += 1 } func (reqLimit *RequestLimitService) IsAvailable() bool { reqLimit.Lock.Lock() defer reqLimit.Lock.Unlock() return reqLimit.ReqCount < reqLimit.MaxCount } var RequestLimit = NewRequestLimitService(1 * time.Second, 5) /** 测试 ab -n 7 -c 7 http://192.168.0.130:9001/ */ func helloHandler(w http.ResponseWriter, r *http.Request) { if RequestLimit.IsAvailable() { RequestLimit.Increase() fmt.Println(RequestLimit.ReqCount) io.WriteString(w, "Hello world!\n") } else { fmt.Println("Reach request limiting!") io.WriteString(w, "Reach request limit!\n") } } func main() { fmt.Println("Server Started!") http.HandleFunc("/", helloHandler) http.ListenAndServe(":9001", nil) } ``` </details> <br/> 缺陷:任然可以在短时间(如 1s )内达到很高的并发