原子计数器
最后更新于:2022-04-02 03:09:11
[TOC]
### 原子计数器
实例:go 实现原子计数器的限流
缺陷:任然可以在短时间(如 1s )内达到很高的并发
';
main.go
``` 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) } ```缺陷:任然可以在短时间(如 1s )内达到很高的并发