思路:
1 某IP地址每分钟的访问次数记录
以IP+当前分钟为key 在redis 中记录某个IP的调用次数,缓存过期时间为60缓。
2 限制调用
如果[1]的值超过阈值,则在redis中写入 ip+limited 为key的一个键值对,缓存过期时间即是不允许API再被这个IP调用的时间,比如100秒。
当API在调用的时候,判断redis中是否存在 ip+limited的这个键值对,如果存,返回频率受限的错误码。
伪代码:
bool isLimted(String ip) {
// 用来判断是否IP 受限的KEY
String attackRejectKey = "attackReject:" + ip;
// 判断 redis 是否存在 attackRejectKey
if redis.get(attackRejectKey)
return true
// 用来记录IP 一分钟内访问次数的KEY
int minute = 获取当前时间的分钟字段
String requestCountKey = "requestCount:" + ip + ":" + minutes;
// 判断 redis 是否存在 requestCountKey
Count = redis.get(requestCountKey)
Count++
if Count > 阈值
redis.set(attackRejectKey, 缓存一段时间)
return false
else
redis.set(requestCountKey, Count)
return true
}