php之任務隊列

http://blog.s135.com/httpsqs/

 

 

例如:郵件隊列、任務隊列、消息隊列、Feed隊列
用戶註冊成功,而不是直接給用戶發送email,而是把新註冊的用戶的email插入到郵件任務隊列中。由服務器給用戶發送郵件。發送成功或發送N次失敗的將從隊列中清除。

 

-------------------------------

如果是普通的網站,如平均每秒產生的隊列消息不超過上百,則用低成本數據庫+輪詢程序,完全可行.

具體思路如下:

1. 當產生消息時,使用MySQL的表保存產生的新隊列消息,並記錄一些運行參數
2. 服務器上開啓cron(Linux),或開啓自動刷新的瀏覽器窗口(Windows),比如按半分鐘運行一次輪詢程序
3. 這些輪詢程序每次取出一些隊列消息,進行處理,處理成功或是處理失敗N次後,刪除MySQL隊列表中的相關記錄

如此反覆,即可實現.我覺得這個方式的優點是:
1. 實現最爲容易,可行性最好
2. 低成本的開發或是平臺部署成本 

在我們的生產環境中,這種方式得到了大量實踐,表現良好.


當然,如果確實是"高性能",那麼這個問題更不問題,既然需要高性能,說明網站的規模不一般,既然規模不一般,還會缺錢嗎? 不缺錢,就可以找這方面的專家去解決.

 

 

 

 

 

 

-------------------------------

 

/**  
* 使用共享內存的PHP循環內存隊列實現  
* 支持多進程, 支持各種數據類型的存儲,需要pcntl擴展的支持。  
* 注: 完成入隊或出隊操作,儘快使用unset(), 以釋放臨界區  
*  
* @author [email protected]  
* @created 2009-12-23   
*/  
class SHMQueue   
{   
    private $maxQSize = 0; // 隊列最大長度   
       
    private $front = 0; // 隊頭指針   
    private $rear = 0;  // 隊尾指針   
       
    private $blockSize = 256;  // 塊的大小(byte)   
    private $memSize = 25600;  // 最大共享內存(byte)   
    private $shmId = 0;   
       
    private $filePtr = './shmq.ptr';   
       
    private $semId = 0;   
    public function __construct()   
    {          
        $shmkey = ftok(__FILE__, 't');   
           
        $this->shmId = shmop_open($shmkey, "c", 0644, $this->memSize );   
        $this->maxQSize = $this->memSize / $this->blockSize;   
           
         // 申請一個信號量   
        $this->semId = sem_get($shmkey, 1);   
        sem_acquire($this->semId); // 申請進入臨界區           
           
        $this->init();   
    }   
       
    private function init()   
    {   
        if ( file_exists($this->filePtr) ){   
            $contents = file_get_contents($this->filePtr);   
            $data = explode( '|', $contents );   
            if ( isset($data[0]) && isset($data[1])){   
                $this->front = (int)$data[0];   
                $this->rear  = (int)$data[1];   
            }   
        }   
    }   
       
    public function getLength()   
    {   
        return (($this->rear - $this->front + $this->memSize) % ($this->memSize) )/$this->blockSize;   
    }   
       
    public function enQueue( $value )   
    {   
        if ( $this->ptrInc($this->rear) == $this->front ){ // 隊滿   
            return false;   
        }   
           
        $data = $this->encode($value);   
        shmop_write($this->shmId, $data, $this->rear );   
        $this->rear = $this->ptrInc($this->rear);   
        return true;   
    }   
           
    public function deQueue()   
    {   
        if ( $this->front == $this->rear ){ // 隊空   
            return false;   
        }   
        $value = shmop_read($this->shmId, $this->front, $this->blockSize-1);   
        $this->front = $this->ptrInc($this->front);   
        return $this->decode($value);   
    }   
       
    private function ptrInc( $ptr )   
    {   
        return ($ptr + $this->blockSize) % ($this->memSize);   
    }   
       
    private function encode( $value )   
    {   
        $data = serialize($value) . "__eof";   
        if ( strlen($data) > $this->blockSize -1 ){   
            throw new Exception(strlen($data)." is overload block size!");   
        }   
        return $data;   
    }   
       
    private function decode( $value )   
    {   
        $data = explode("__eof", $value);   
        return unserialize($data[0]);          
    }   
       
    public function __destruct()   
    {   
        $data = $this->front . '|' . $this->rear;   
        file_put_contents($this->filePtr, $data);   
           
        sem_release($this->semId); // 出臨界區, 釋放信號量   
    }   
}



使用的樣例代碼如下:

// 進隊操作
$shmq = new SHMQueue();   
$data = 'test data';   
$shmq->enQueue($data);   
unset($shmq);   
// 出隊操作   
$shmq = new SHMQueue();   
$data = $shmq->deQueue();   
unset($shmq);


PHP下用Memcache 實現消息隊列


   Memcache 一般用於緩存服務。但是很多時候,比如一個消息廣播系統,需要一個消息隊列。直接從數據庫取消息,負載往往不行。如果將整個消息隊列用一個key緩存到memcache裏面,

對於一個很大的消息隊列,頻繁進行進行大數據庫的序列化 和 反序列化,有太耗費。下面是我用PHP 實現的一個消息隊列,只需要在尾部插入一個數據,就操作尾部,不用操作整個消息隊列進行讀取,與操作。但是,這個消息隊列不是線程安全的,我只是儘量的避免了衝突的可能性。如果消息不是非常的密集,比如幾秒鐘才一個,還是可以考慮這樣使用的。

    如果你要實現線程安全的,一個建議是通過文件進行鎖定,然後進行操作。下面是代碼:

class Memcache_Queue
{
    
private $memcache;

    
private $name;

    
private $prefix;

    
function __construct($maxSize, $name, $memcache, $prefix = "__memcache_queue__")
    {
        
if ($memcache == null) {
            
throw new Exception("memcache object is null, new the object first.");
        }
        
$this->memcache = $memcache;
        
$this->name = $name;
        
$this->prefix = $prefix;

        
$this->maxSize = $maxSize;
        
$this->front = 0;
        
$this->real = 0;
        
$this->size = 0;
    }

    
function __get($name)
    {
        
return $this->get($name);
    }

    
function __set($name, $value
    {
        
$this->add($name, $value);
        
return $this;
    }

    
function isEmpty() 
    {
        
return $this->size == 0;
    }

    
function isFull()
    {
        
return $this->size == $this->maxSize;
    }

    
function enQueue($data)
    {
        
if ($this->isFull()) {
            
throw new Exception("Queue is Full");
        }
        
$this->increment("size");
        
$this->set($this->real, $data);
        
$this->set("real", ($this->real + 1% $this->maxSize);
        
return $this;
    }

    
function deQueue()
    {
        
if ($this->isEmpty()) {
            
throw new Exception("Queue is Empty");
        }
        
$this->decrement("size");
        
$this->delete($this->front);
        
$this->set("front", ($this->front + 1% $this->maxSize);
        
return $this;
    }

    
function getTop()
    {
        
return $this->get($this->front);
    }

    
function getAll()
    {
        
return $this->getPage();
    }

    
function getPage($offset = 0, $limit = 0)
    {
        
if ($this->isEmpty() || $this->size < $offset) {
            
return null;
        }
        
$keys[] = $this->getKeyByPos(($this->front + $offset% $this->maxSize);
        
$num = 1;
        
for ($pos = ($this->front + $offset + 1% $this->maxSize; $pos != $this->real; $pos = ($pos + 1% $this->maxSize) 
        {
             
$keys[] = $this->getKeyByPos($pos);
             
$num++;
             
if ($limit > 0 && $limit == $num) {
                 
break;
             }
        }
        
return array_values($this->memcache->get($keys));
    }

    
function makeEmpty()
    {
        
$keys = $this->getAllKeys();
        
foreach ($keys as $value) {
            
$this->delete($value);
        }
        
$this->delete("real");
        
$this->delete("front");
        
$this->delete("size");
        
$this->delete("maxSize");
    }

    
private function getAllKeys()
    {
        
if ($this->isEmpty()) 
        {
            
return array();
        }
        
$keys[] = $this->getKeyByPos($this->front);
        
for ($pos = ($this->front + 1% $this->maxSize; $pos != $this->real; $pos = ($pos + 1% $this->maxSize) 
        {
            
$keys[] = $this->getKeyByPos($pos);
        }
        
return $keys;
    }

    
private function add($pos, $data
    {
        
$this->memcache->add($this->getKeyByPos($pos), $data);
        
return $this;
    }

    
private function increment($pos)
    {
        
return $this->memcache->increment($this->getKeyByPos($pos));
    }

    
private function decrement($pos
    {
        
$this->memcache->decrement($this->getKeyByPos($pos));
    }

    
private function set($pos, $data
    {
        
$this->memcache->set($this->getKeyByPos($pos), $data);
        
return $this;
    }

    
private function get($pos)
    {
        
return $this->memcache->get($this->getKeyByPos($pos));
    }

    
private function delete($pos)
    {
        
return $this->memcache->delete($this->getKeyByPos($pos));
    }

    
private function getKeyByPos($pos)
    {
        
return $this->prefix . $this->name . $pos;
    }
}






轉自:http://zhengdl126.iteye.com/blog/816575
參考:http://www.yuansir-web.com/2012/09/22/php-%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98%E4%BB%A5%E5%8F%8A%E5%88%A9%E7%94%A8%E5%85%B1%E4%BA%AB%E5%86%85%E5%AD%98%E5%AE%9E%E7%8E%B0%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/

http://www.laruence.com/2008/04/21/101.html



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章