A simple access frequency control based on redis

Ideas:

1 Record of the number of visits per minute of an IP address

Record the number of calls to an IP in redis with IP+current minute as the key, and the cache expiration time is 60.

2 Restrict calls

If the value of [1] exceeds the threshold, write a key-value pair with ip+limited as the key in redis, and the cache expiration time is the time that the API is not allowed to be called by this IP, such as 100 seconds.

When the API is being called, it is judged whether the key-value pair of ip+limited exists in redis, and if so, the frequency-limited error code is returned.

Fake code:

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
}

 

Guess you like

Origin blog.csdn.net/wuzhong8809/article/details/107227784