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));
}
}
} 相关推荐
txj 2020-08-17
亦碎流年 2020-06-18
middleware0 2020-06-13
anglehearts 2020-04-03
枫叶上的雨露 2020-05-04
zhangtianshun 2020-05-03
博了个客 2020-04-29
sunzxh 2020-04-22
八角塘塘主 2020-04-09
GavinZhera 2020-04-08
郭宇 2020-02-22
Cheetahcubs 2020-02-12
middleware0 2020-02-11
wangxiaoxue 2020-01-23
guweiyuthinker 2020-01-20
MLXY 2020-01-21