当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP队列用法实例

发布:smiling 来源: PHP粉丝网  添加日期:2021-04-24 13:50:56 浏览: 评论:0 

这篇文章主要介绍了PHP队列用法,以实例形式详细讲述了PHP队列的实现与各种常用的操作,非常具有参考借鉴价值,需要的朋友可以参考下。

本文实例讲述了PHP队列用法。分享给大家供大家参考。具体分析如下:

什么是队列,是先进先出的线性表,在具体应用中通常用链表或者数组来实现,队列只允许在后端进行插入操作,在前端进行删除操作。

什么情况下会用了队列呢,并发请求又要保证事务的完整性的时候就会用到队列,当然不排除使用其它更好的方法,知道的不仿说说看。

队列还可以用于减轻数据库服务器压力,我们可以将不是即时数据放入到队列中,在数据库空闲的时候或者间隔一段时间后执行。比如访问计数器,没有必要即时的执行访问增加的Sql,在没有使用队列的时候sql语句是这样的,假设有5个人访问:

  1. update table1 set count=count+1 where id=1 
  2. update table1 set count=count+1 where id=1 
  3. update table1 set count=count+1 where id=1 
  4. update table1 set count=count+1 where id=1 
  5. update table1 set count=count+1 where id=1 

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

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

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

下面一个队列类:

  1. /** 
  2. * 队列 
  3. * 
  4. * @author jaclon 
  5. * 
  6. */ 
  7. class Queue 
  8. { 
  9. private $_queue = array(); 
  10. protected $cache = null; 
  11. protected $queuecachename; 
  12.  
  13. /** 
  14. * 构造方法 
  15. * @param string $queuename 队列名称 
  16. */ 
  17. function __construct($queuename) 
  18. { 
  19.  
  20. $this->cache =& Cache::instance(); 
  21. $this->queuecachename = 'queue_' . $queuename; 
  22.  
  23. $result = $this->cache->get($this->queuecachename); 
  24. if (is_array($result)) { 
  25. $this->_queue = $result; 
  26. } 
  27. } 
  28.  
  29. /** 
  30. * 将一个单元单元放入队列末尾 
  31. * @param mixed $value 
  32. */ 
  33. function enQueue($value) 
  34. { 
  35. $this->_queue[] = $value; 
  36. $this->cache->set($this->queuecachename, $this->_queue); 
  37.  
  38. return $this; 
  39. } 
  40.  
  41. /** 
  42. * 将队列开头的一个或多个单元移出 
  43. * @param int $num 
  44. */ 
  45. function sliceQueue($num = 1) 
  46. { 
  47. if (count($this->_queue) < $num) { 
  48. $num = count($this->_queue); 
  49. } 
  50. $output = array_splice($this->_queue, 0, $num); 
  51. $this->cache->set($this->queuecachename, $this->_queue); 
  52.  
  53. return $output; 
  54. } 
  55.  
  56. /** 
  57. * 将队列开头的单元移出队列 
  58. */ 
  59. function deQueue() 
  60. { 
  61. $entry = array_shift($this->_queue); 
  62. $this->cache->set($this->queuecachename, $this->_queue); 
  63.  
  64. return $entry; 
  65. } 
  66.  
  67. /** 
  68. * 返回队列长度 
  69. */ 
  70. function size() 
  71. { 
  72. return count($this->_queue); 
  73. } 
  74.  
  75. /** 
  76. * 返回队列中的第一个单元 
  77. */ 
  78. function peek() 
  79. { 
  80. return $this->_queue[0]; 
  81. } 
  82.  
  83. /** 
  84. * 返回队列中的一个或多个单元 
  85. * @param int $num 
  86. */ 
  87. function peeks($num) 
  88. { 
  89. if (count($this->_queue) < $num) { 
  90. $num = count($this->_queue); 
  91. } 
  92. return array_slice($this->_queue, 0, $num); 
  93. } 
  94. //www.phpfensi.com 
  95. /** 
  96. * 消毁队列 
  97. */ 
  98. function destroy() 
  99. { 
  100. $this->cache->remove($this->queuecachename); 
  101. } 
  102. } 

希望本文所述对大家的PHP程序设计有所帮助。

Tags: PHP队列

分享到: