码迷,mamicode.com
首页 > 其他好文 > 详细

redis 简单限流

时间:2020-05-09 19:26:33      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:void   key   stack   except   ati   catch   out   mat   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 简单限流

标签:void   key   stack   except   ati   catch   out   mat   redis   

原文地址:https://www.cnblogs.com/mmh760/p/12859144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!