php成熟的队列,PHP队列你一定用的到

PHP队列简单介绍

什么是队列,是先进先出的线性表,在具体应用中通常用链表或者数组来实现,队列只允许在后端进行插入操作,在前端进行删除操作。 什么情况下会用了队列呢,并发请求又要保证事务的完整性的时候就会用到队列,当然不排除使用其它更好的方法。 队列还可以用于减轻数据库服务器压力,我们可以将不是即时数据放入到队列中,在数据库空闲的时候或者间隔一段时间后执行。 比如访问计数器,没有必要即时的执行访问增加的Sql,在没有使用队列的时候sql语句是这样的,假设有5个人访问:

update table1 set count=count+1 where id=1

update table1 set count=count+1 where id=1

update table1 set count=count+1 where id=1

update table1 set count=count+1 where id=1

update table1 set count=count+1 where id=1

而使用队列这后就可以这样:

update table1 set count=count+5 where id=1

减少sql请求次数,从而达到减轻服务器压力的效果, 当然访问量不是很大网站根本没有这个必要。

队列的实现

简单的实现

第一个元素作为队头,最后一个元素作为队尾

/**  * 队列就是这么简单  *  */

$array =  array('PHP', 'JAVA');

array_push($array, 'PYTHON'); //入队列

array_shift($array); //出队列

PHP 队列类

private    $_queue = [];

protected  $cache  = null;

protected  $queuecachename;

/**     * 构造方法     * Queue constructor.     * @param $queuename     */

public function __construct($queuename ) {

$this->cache = & Cache::instance();

$this->queuecachename = 'queue_'.$queuename;

$result = $this->cache->get($this->queuecachename);

if(is_array($result)) {

$this->_queue = $result;

}

}

/**     * 将一个单元放入队列末尾     * @param $value     * @return $this     */

public function enQueue($value) {

$this->_queue[]=$value;

$this->cache->set($this->queuecachename,$this->_queue);

return $this;

}

/**     * 将队列开头的一个或多个单元移除     * @param int $num     * @return array     */

public function sliceQueue($num = 1) {

if(count($this->_queue)

$num = count($this->_queue);

}

$output = array_slice($this->_queue,0,$num);

$this->cache->set($this->queuecachename,$this->_queue);

return $output;

}

/**     * 将队列开头的单元移出队列     * @return mixed     */

public function deQueue() {

$entry = array_shift($this->_queue);

$this->cache->set($this->queuecachename,$this->_queue);

return $entry;

}

/**     * 获取队列的长度     * @return int     */

public function size() {

return count($this->_queue);

}

/**     * 获取队列中的第一个     * @return mixed     */

public function peek() {

return $this->_queue[0];

}

/**     * 返回队列中的一个或者多个单元     * @param $num     * @return array     */

public function peeks($num){

if(count($this->_queue)

$num = count($this->_queue);

}

return array_slice($this->_queue,0,$num);

}

/**     *  销毁队列     */

public function destroy() {

$this->cache->remove($this->queuecachename);

}}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值