zoukankan      html  css  js  c++  java
  • 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
    }
    

      

  • 相关阅读:
    curl
    Bazel 国内镜像源加速下载 + 编译gvisor
    go proxy 代理
    netstack gvisor
    rust libc
    gVisor in depth
    Unikernel
    Unikernel初体验
    github 文本编辑
    cloud-hypervisor coredump
  • 原文地址:https://www.cnblogs.com/gm-201705/p/7902697.html
Copyright © 2011-2022 走看看