美文网首页
Redis-简单分布式限流

Redis-简单分布式限流

作者: zhangsanzhu | 来源:发表于2018-12-30 22:31 被阅读0次

    Redis-简单分布式限流

    限流方式

    漏斗式: 应对突发会直接溢出,拒绝服务了.
    令牌桶式: 应对突发会比较好,毕竟是以一定的额速率往桶里放令牌,每次请求取一个.

    介绍

    需要读者花一定的时间好好啃。它的整体思路就是:
    每一个行为到来时,都维护一次时间窗口。将时间窗口外的记录全部清理掉,只保留窗口内的记录。
    zset 集合中只有 score 值非常重要,value 值没有特别的意义,只需要保证它是唯一的就可以了。

    因为这几个连续的 Redis 操作都是针对同一个 key 的,使用 pipeline 可以显著提升 Redis 存取效率。
    但这种方案也有缺点,因为它要记录时间窗口内所有的行为记录,如果这个量很大,比如限定 60s 内操作不得超过 100w 次这样的参数,
    它是不适合做这样的限流的,因为会消耗大量的存储空间

    public class SimpleRateLimiter {
    
        private Jedis jedis ;
    
        public SimpleRateLimiter(Jedis jedis) {
            this.jedis = jedis;
        }
    
        private boolean isActionAllowed(String userId, String actionKey, int period, int maxCount) {
            String key = String.format("hist:%s:%s", userId, actionKey);
            long nowTs = System.currentTimeMillis();
            Pipeline pipe = jedis.pipelined();
            pipe.multi();
            pipe.zadd(key, nowTs, "" + nowTs);
            pipe.zremrangeByScore(key, 0, nowTs - period * 1000);
            Response<Long> count = pipe.zcard(key);
            pipe.expire(key, period + 1);
            pipe.exec();
            try {
                pipe.close();
            } catch (IOException e) {
                System.out.println(e);
            }
            return count.get() <= maxCount;
        }
    
        public static void main(String[] args) {
            Jedis jedis = new Jedis("127.0.0.1", 6379);
            SimpleRateLimiter limiter = new SimpleRateLimiter(jedis);
            for (int i = 0; i < 20; i++) {
                System.out.println(limiter.isActionAllowed("laoqian", "reply", 60, 5));
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Redis-简单分布式限流

          本文链接:https://www.haomeiwen.com/subject/prqulqtx.html