欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP隊列用法實例

 更新時間:2014年11月05日 15:26:31   投稿:shichen2014  
這篇文章主要介紹了PHP隊列用法,以實例形式詳細講述了PHP隊列的實現(xiàn)與各種常用的操作,非常具有參考借鑒價值,需要的朋友可以參考下

本文實例講述了PHP隊列用法。分享給大家供大家參考。具體分析如下:

什么是隊列,是先進先出的線性表,在具體應(yīng)用中通常用鏈表或者數(shù)組來實現(xiàn),隊列只允許在后端進行插入操作,在前端進行刪除操作。

什么情況下會用了隊列呢,并發(fā)請求又要保證事務(wù)的完整性的時候就會用到隊列,當(dāng)然不排除使用其它更好的方法,知道的不仿說說看。

隊列還可以用于減輕數(shù)據(jù)庫服務(wù)器壓力,我們可以將不是即時數(shù)據(jù)放入到隊列中,在數(shù)據(jù)庫空閑的時候或者間隔一段時間后執(zhí)行。比如訪問計數(shù)器,沒有必要即時的執(zhí)行訪問增加的Sql,在沒有使用隊列的時候sql語句是這樣的,假設(shè)有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請求次數(shù),從而達到減輕服務(wù)器壓力的效果, 當(dāng)然訪問量不是很大網(wǎng)站根本沒有這個必要。
下面一個隊列類:

復(fù)制代碼 代碼如下:
/**
* 隊列
*
* @author jaclon
*
*/
class Queue
{
private $_queue = array();
protected $cache = null;
protected $queuecachename;
 
/**
* 構(gòu)造方法
* @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程序設(shè)計有所幫助。

相關(guān)文章

最新評論