前言

最近在开发一个网站域名证书在线申请的项目,有环智中诚的经销商资格,他的API限制为每分钟可请求 300 次,考虑到后面量比较大,想到了可以使用队列来解决限制的问题,参考了网上的实现原理,写了一份实现代码给大家分享出来。

实现代码

<?php

/**
 * Class queue
 * @author 教书先生
 * @link https://blog.oioweb.cn/72.html
 * @time 2021年2月25日17:46:23
 */
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();

运行结果

小杨入队成功!
教书先生入队成功!
孙悟空入队成功!
当前队首:小杨
摇摆羊:我一来咋就满了!(队满不能入队,请等待!)
小杨出队成功!
斯沃特入队成功!
教书先生出队成功!
孙悟空出队成功!
斯沃特出队成功!
队空不能出队!
最后修改:2021 年 04 月 01 日
如果觉得我的文章对你有用,请随意赞赏