Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize current limit in php

Shulou Source: shulou.com Published: 2022-06-01 06:18:23 09月15日 Update

This article is to share with you about how to achieve current limit in php. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

What is interface current limit?

So what is current restriction? As the name implies, current restriction is to limit traffic, including concurrent traffic and total traffic within a certain period of time, just like you have a broadband packet of 1 G of traffic, which is gone when it is used up, so control your use frequency and the total consumption of a single use. By limiting the current, we can well control the qps of the system, so as to protect the stability of the system or interface server.

Common algorithms of Interface current limit

Counter method

The counter method is the simplest and easiest to implement in the current limiting algorithm. For example, we stipulate that for interface A, we cannot have more than 100 visits per minute. So we can do this: at the beginning, we can set a counter counter, every time a request comes, counter is incremented by 1. If the value of counter is greater than 100 and the interval between the request and the first request is less than 1 minute, then the number of requests is too many. If the interval between the request and the first request is more than 1 minute, and the value of counter is still within the current limit, reset counter. The diagram of the algorithm is as follows:

The pseudo code is as follows: class CounterDemo {

Private $timeStamp

Public $reqCount=0

Maximum number of requests in the public $limit=100;// time window

Public $interval=1000; / / time window ms

Public function _ construct ()

{

$this- > timeStamp=time ()

}

Public function grant () {

$now=time ()

If ($nowtimeStamp+$this- > interval) {

/ / within the time window

$this- > reqCount++

Return $this- > reqCountlimit

} else {

/ / reset after timeout

$this- > timeStamp=time ()

$this- > reqCount=1

Return true

}

}

}

Thank you for reading! This is the end of the article on "how to achieve current restriction in php". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Time interface algorithm traffic counter content time more article system control good practical maximum as the name implies code finished that is commonly used total traffic Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Apple Microsoft Huawei Linux