An IP Frequency Control Method Based on Redis's 10 lines of code

Source: Internet
Author: User
Tags redis cluster

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:

 
 
  1. R3c: CRedisClient redis ("127.0.0.1: 6379,127.0 .0.1: 6380 ");
  2. Int ret = redis. incrby (ip, 1 );
  3. If (ret> 1000) // exceeds the frequency
  4. {
  5. }
  6. Else // Access Control
  7. {
  8. If (1 = ret)
  9. Redis. expire (ip, 2); // The frequency is controlled to 1000 accesses within 2 seconds
  10. }

Complete example:

 
 
  1. // Https://github.com/eyjian/r3c
  2. # Include

  3. Int main ()
  4. {
  5. Std: string ip = "127.0.0.1 ";
  6. R3c: CRedisClient redis ("10.223.25.102: 6379 ");
  7. R3c: set_debug_log_write (NULL );
  8. For (int I = 0; I <100000; ++ I)
  9. {
  10. Int ret = redis. incrby (ip, 1 );
  11. If (ret> 1000) // restrict a single IP address to access up to 1000 times every 2 seconds
  12. {
  13. Printf ("[OVER] exceeds the frequency, restrict access \ n ");
  14. }
  15. Else
  16. {
  17. If (1 = ret)
  18. {
  19. Redis. expire (ip, 2); // The frequency is set to 2 seconds.
  20. Printf ("[FIRST] FIRST Time, access allowed \ n ");
  21. }
  22. Else
  23. {
  24. Printf ("[OK] access allow \ n ");
  25. }
  26. }
  27. }
  28. Redis. del (ip );
  29. Return 0;
  30. }



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.