[GO]go redis實現滑動窗口限流-redis版


上一篇是單機當前進程的滑動窗口限流 , 這一個是使用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
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM