An IP Frequency Control Method Based on Redis's 10 lines of code
Advantage: supports Frequency Control of massive access. You only need to add a Redis machine. A single Redis node (only occupies one cpu core) can support processing at least 60 thousand/s.
IP frequency limit is a common requirement. Based on Redis, you can easily limit the IP frequency. The specific method is to use Redis's key expiration and atomic addition and subtraction.
The IP address is used as the key and the frequency is the key expiration time. For example, if the frequency of a single IP address is limited to 100 within 2 seconds, the key expiration time is 2 seconds, the implementation based on r3c (a Redis Cluster C ++ Client) is roughly as follows:
- R3c: CRedisClient redis ("127.0.0.1: 6379,127.0 .0.1: 6380 ");
- Int ret = redis. incrby (ip, 1 );
- If (ret> 1000) // exceeds the frequency
- {
- }
- Else // Access Control
- {
- If (1 = ret)
- Redis. expire (ip, 2); // The frequency is controlled to 1000 accesses within 2 seconds
- }
Complete example:
- // Https://github.com/eyjian/r3c
- # Include
- Int main ()
- {
- Std: string ip = "127.0.0.1 ";
- R3c: CRedisClient redis ("10.223.25.102: 6379 ");
- R3c: set_debug_log_write (NULL );
- For (int I = 0; I <100000; ++ I)
- {
- Int ret = redis. incrby (ip, 1 );
- If (ret> 1000) // restrict a single IP address to access up to 1000 times every 2 seconds
- {
- Printf ("[OVER] exceeds the frequency, restrict access \ n ");
- }
- Else
- {
- If (1 = ret)
- {
- Redis. expire (ip, 2); // The frequency is set to 2 seconds.
- Printf ("[FIRST] FIRST Time, access allowed \ n ");
- }
- Else
- {
- Printf ("[OK] access allow \ n ");
- }
- }
- }
- Redis. del (ip );
- Return 0;
- }