前言
最近想对接一个API,接口限制为每分钟可请求 300 次,考虑到后面量比较大,想到了可以使用队列来解决限制的问题,参考了网上的实现原理,写了一份实现代码给大家分享出来。
实现代码
<?php
/**
* PHP队列
* Class queue
*/
class queue
{
protected $front;//队头
protected $rear;//队尾
protected $queue = [
'0' => '队尾'
];//存储队列
protected $maxsize;//最大数
public function __construct($size)
{
$this->initQ($size);
}
//初始化队列
private function initQ($size)
{
$this->front = 0;
$this->rear = 0;
$this->maxsize = $size;
}
//判断队空
public function QIsEmpty()
{
return $this->front === $this->rear;
}
//判断队满
public function QIsFull()
{
return ($this->front - $this->rear) === $this->maxsize;
}
//获取队首数据
public function getFrontDate()
{
echo "当前队首:".$this->queue[$this->front]."<br>";
}
//入队
public function InQ($data)
{
if ($this->QIsFull()) {
echo $data . ":我一来咋就满了!(队满不能入队,请等待!)<br>";
} else {
$this->front++;
for ($i = $this->front; $i > $this->rear; $i--) {
if ($this->queue[$i]) {
unset($this->queue[$i]);
}
$this->queue[$i] = $this->queue[$i - 1];
}
$this->queue[$this->rear + 1] = $data;
echo $data . '入队成功!<br>';
}
}
//出队
public function OutQ()
{
if ($this->QIsEmpty()) {
echo "队空不能出队!<br>";
} else {
echo $this->queue[$this->front]."出队成功!<br>";
unset($this->queue[$this->front]);
$this->front--;
}
}
}
$q = new queue(3);
$q->InQ("小王");
$q->InQ('小明');
$q->InQ('小丽');
$q->getFrontDate();
$q->InQ('小赵');
$q->OutQ();
$q->InQ("小张");
$q->OutQ();
$q->OutQ();
$q->OutQ();
$q->OutQ();
666