温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP队列的用法介绍

发布时间:2021-08-09 21:52:31 来源:亿速云 阅读:131 作者:chen 栏目:开发技术

这篇文章主要讲解了“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请求次数,从而达到减轻服务器压力的效果, 当然访问量不是很大网站根本没有这个必要。
下面一个队列类:

复制代码 代码如下:

/**
* 队列
*
* @author jaclon
*
*/
class Queue
{
private $_queue = array();
protected $cache = null;
protected $queuecachename;
 
/**
* 构造方法
* @param string $queuename 队列名称
*/
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 mixed $value
*/
function enQueue($value)
{
$this->_queue[] = $value;
$this->cache->set($this->queuecachename, $this->_queue);
 
return $this;
}
 
/**
* 将队列开头的一个或多个单元移出
* @param int $num
*/
function sliceQueue($num = 1)
{
if (count($this->_queue) < $num) {
$num = count($this->_queue);
}
$output = array_splice($this->_queue, 0, $num);
$this->cache->set($this->queuecachename, $this->_queue);
 
return $output;
}
 
/**
* 将队列开头的单元移出队列
*/
function deQueue()
{
$entry = array_shift($this->_queue);
$this->cache->set($this->queuecachename, $this->_queue);
 
return $entry;
}
 
/**
* 返回队列长度
*/
function size()
{
return count($this->_queue);
}
 
/**
* 返回队列中的第一个单元
*/
function peek()
{
return $this->_queue[0];
}
 
/**
* 返回队列中的一个或多个单元
* @param int $num
*/
function peeks($num)
{
if (count($this->_queue) < $num) {
$num = count($this->_queue);
}
return array_slice($this->_queue, 0, $num);
}
 
/**
* 消毁队列
*/
function destroy()
{
$this->cache->remove($this->queuecachename);
}
}

感谢各位的阅读,以上就是“PHP队列的用法介绍”的内容了,经过本文的学习后,相信大家对PHP队列的用法介绍这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI