redis实现api限流

redis官方给出了参考文档:INCR

这里参考第一种方法,使用token bucket实现:每个用户每秒有一个Counter;

func RateLimiter(uid string, rlType string) bool {
        // one key per user, per second
        k := uid + ":" + strconv.Itoa(int(time.Now().Unix())) + ":" + rlType

        limit := rwRate[uid][0]
        if rlType == "read" {
                limit = rwRate[uid][1]
        }

        count, err := rds.Get(k).Result()
        c, _ := strconv.Atoi(count)
        if err != redis.Nil && c >= limit {
                log.Println("too many requests per second")
                atomic.AddUint64(&DeniedCount, 1)
                return false
        }

        pipe := rds.Pipeline()
        pipe.Incr(k)
        pipe.Expire(k, time.Second*5)
        if _, err = pipe.Exec(); err != nil {
                log.Println("redis exec error: ", err)
        }
        return true
}

  

原文地址:https://www.cnblogs.com/gm-201705/p/7902697.html