您的位置:首页 > 数据库 > Redis

利用redis做频率限制第一篇

2016-04-30 21:18 645 查看
public Result checkRateLimit(String clientIp, int ipTime, int ipCount) {
// 每个ip的redis的key都不一样
String ipRateKey = "ipRates:" + clientIp;
System.out.println(ipRateKey);
long time = commonRedis.ttl(ipRateKey);
System.out.println("ttl time: " + time);
if (time > 0) {
System.out.println(ipRateKey + "还未过期");
} else if (time == -1) {
System.out.println(ipRateKey + "不存在或是设置过期时间");
}
String ipRates = commonRedis.get(ipRateKey);
Integer ipTimes = 0;
if (ipRates == null) {
// 没有此键
commonRedis.set(ipRateKey, "1");
commonRedis.expire(ipRateKey, 1000);
ipTimes = 1;
} else {
// 有此键
ipTimes = Integer.parseInt(ipRates);
commonRedis.incr(ipRateKey);
}
System.out.println("ipTimes: " + ipTimes);
if (ipTimes > ipCount) {
return new Result(-1, "该ip频率受限,每分钟最多登录" + ipCount + "次");
}
return new Result(0, "success");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: