找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1019|回复: 0
打印 上一主题 下一主题

PHP队列用法实例

[复制链接]

2588

主题

2588

帖子

7694

积分

论坛元老

Rank: 8Rank: 8

积分
7694
跳转到指定楼层
楼主
发表于 2018-2-14 05:53:19 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            本文实例讲述了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请求次数,从而达到减轻服务器压力的效果, 当然访问量不是很大网站根本没有这个必要。
下面一个队列类:
[U]复制代码[/U] 代码如下:/**
* 队列
*
* @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) _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) _queue);
}
return array_slice($this->_queue, 0, $num);
}

/**
* 消毁队列
*/
function destroy()
{
$this->cache->remove($this->queuecachename);
}
}
希望本文所述对大家的PHP程序设计有所帮助。
            
            
您可能感兴趣的文章:
  • PHP使用数组实现队列
  • PHP中使用数组实现堆栈数据结构的代码
  • php中使用redis队列操作实例代码
  • 关于PHP堆栈与列队的学习
  • php实现的双向队列类实例
  • PHP 数据结构队列(SplQueue)和优先队列(SplPriorityQueue)简单使用实例
  • PHP消息队列用法实例分析
  • PHP基于Redis消息队列实现发布微博的方法
  • PHP基于堆栈实现的高级计算器功能示例
  • PHP栈的定义、入栈出栈方法及基于堆栈实现的计算器完整实例
  • PHP基于数组实现的堆栈和队列功能示例
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端