<?php/** * CacheLock 進程鎖,主要用來進行cache失效時的單進程cache擷取,防止過多的SQL請求穿透到資料庫 * 用於解決PHP在並發時候的鎖控制,通過檔案/eaccelerator進行進程間鎖定 * 如果沒有使用eaccelerator則進行進行檔案鎖處理,會做對應目錄下產生對應粒度的鎖 * 使用了eaccelerator則在記憶體中處理,效能相對較高 * 不同的鎖之間並存執行,類似mysql innodb的行級鎖 * 本類在sunli的phplock的基礎上做了少許修改 http://code.google.com/p/phplock * @author yangxinqi * */namespace Common\Business;class PhpLock{ //檔案鎖存放路徑 private $path = null; //檔案控制代碼 private $fp = null; //鎖粒度,設定越大粒度越小 private $hashNum = 100; //cache key private $name; //是否存在eaccelerator標誌 private $eAccelerator = false; /** * 建構函式 * 傳入鎖的存放路徑,及cache key的名稱,這樣可以進行並發 * @param string $path 鎖的存放目錄,以"/"結尾 * @param string $name cache key */ public function __construct($name,$path='lock\\') { $app_path = str_replace('ThinkPHP/', '', THINK_PATH); $is_cli = php_sapi_name(); if($is_cli == 'cli' || $is_cli == 'cli_server') { $app_path = trim(APP_PATH, '.'); } else { $app_path = $app_path . trim(APP_PATH, '.'); } $path = $app_path.'/Common/Business/lockfile/'; if(!file_exists($path)) { mkdir($path); chmod($path,777); } //$path .= '/protected/runtime/cache/'; //判斷是否存在eAccelerator,這裡啟用了eAccelerator之後可以進行記憶體鎖提高效率 $this->eAccelerator = function_exists("eaccelerator_lock"); if(!$this->eAccelerator) { //$this->path = $path.($this->_mycrc32($name) % $this->hashNum).'.txt'; $this->path = $path.sha1($name).'.txt'; } $this->name = $name; } /** * crc32 * crc32封裝 * @param int $string * @return int */ private function _mycrc32($string) { $crc = abs (crc32($string)); if ($crc & 0x80000000) { $crc ^= 0xffffffff; $crc += 1; } return $crc; } /** * 加鎖 * Enter description here ... */ public function lock() { //如果無法開啟ea記憶體鎖,則開啟檔案鎖 if(!$this->eAccelerator) { //配置目錄許可權可寫 $this->fp = fopen($this->path, 'w+'); if($this->fp === false) { return false; } return flock($this->fp, LOCK_EX); }else{ return eaccelerator_lock($this->name); } } /** * 解鎖 * Enter description here ... */ public function unlock() { if(!$this->eAccelerator) { if($this->fp !== false) { flock($this->fp, LOCK_UN); clearstatcache(); } //進行關閉 fclose($this->fp); }else{ return eaccelerator_unlock($this->name); } }}