redis 简单限流

Posted Myron的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis 简单限流相关的知识,希望对你有一定的参考价值。

/**
 * @Description: 简单限流
 * @Author : myron
 * @Date : 2020-05-09 17:43
 **/
public class SimpleLimiter {
    private Jedis jedis;
    public SimpleLimiter(Jedis jedis) {
        this.jedis = jedis;
    }
    public 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) {
            e.printStackTrace();
        }
        return count.get() <= maxCount;
    }
    public static void main(String[] args) {
        Jedis jedis = new Jedis();
        SimpleLimiter limiter = new SimpleLimiter(jedis);
        for(int i=0;i<20;i++) {
            //一分钟之内最多回复5次
            System.out.println(limiter.isActionAllowed("myron", "reply", 60, 5));
        }
    }
}

 

以上是关于redis 简单限流的主要内容,如果未能解决你的问题,请参考以下文章

深入Redis简单限流

Redis(07)-ZSET实现简单限流

redis 简单限流

redis 简单限流

一种redis lua 限流方式的简单分析

Redis-Cell令牌桶限流详述