上一篇是單機當前進程的滑動窗口限流 , 這一個是使用go redis list結構實現的滑動窗口限流 , 原理都一樣 , 但是支持分布式
原理可以參考上一篇介紹
func LimitFreqs(queueName string, count uint, timeWindow int64) bool { currTime := time.Now().Unix() length := uint(ListLen(queueName)) if length < count { ListPush(queueName, currTime) return true } //隊列滿了,取出最早訪問的時間 earlyTime, _ := strconv.ParseInt(ListIndex(queueName, int64(length)-1), 10, 64) //說明最早期的時間還在時間窗口內,還沒過期,所以不允許通過 if currTime-earlyTime <= timeWindow { return false } else { //說明最早期的訪問應該過期了,去掉最早期的 ListPop(queueName) ListPush(queueName, currTime) } return true }