title: Distributed current limiter meta:

  • name: description content: Easyswoole provides an Atomic counter-based current limiter that limits the total number of requests in a given time period to achieve a base current limit.
  • name: keywords content: swoole|swoole extension|swoole framework|EasySwoole Distributed | AtomicLimit|Distributed Current Limiter

AtomicLimit

Easyswoole provides a current limiter based on Atomic counters.

Principle

The basic current limit is achieved by limiting the total number of requests in a certain time period. For example, if the maximum number of requests allowed is 200 in 5 seconds, then the theoretical average is 40 and the peak is 200.

Installation

  1. composer require easyswoole/atomic-limit

Sample code

  1. /*
  2. * egUrl http://127.0.0.1:9501/index.html?api=1
  3. */
  4. use EasySwoole\AtomicLimit\AtomicLimit;
  5. AtomicLimit::getInstance()->addItem('default')->setMax(200);
  6. AtomicLimit::getInstance()->addItem('api')->setMax(2);
  7. $http = new swoole_http_server("127.0.0.1", 9501);
  8. AtomicLimit::getInstance()->enableProcessAutoRestore($http,10*1000);
  9. $http->on("request", function ($request, $response) {
  10. if(isset($request->get['api'])){
  11. if(AtomicLimit::isAllow('api')){
  12. $response->write('api success');
  13. }else{
  14. $response->write('api refuse');
  15. }
  16. }else{
  17. if(AtomicLimit::isAllow('default')){
  18. $response->write('default success');
  19. }else{
  20. $response->write('default refuse');
  21. }
  22. }
  23. $response->end();
  24. });
  25. $http->start();

Note that this example uses a custom process plus timer to implement the count timing reset. In fact, it is not worthwhile to use a process to do this. Therefore, the actual production can specify a worker and set a timer to implement.