PHP memcache 環形隊列

來源:互聯網
上載者:User
PHP memcache 環形隊列類。新手,沒咋學過資料結構,因為業務需要,所以只是硬著頭皮類比的! 原形是 oschina上 lusi 分享的PHP memcache 隊列代碼。為使隊列隨時可入可出,且不受int長度越界危險(單鏈採取Head自增的話不作處理有越界可能),所以索性改寫成環形隊列。可能還有BUG,忘見諒!
  1. /**
  2. * PHP memcache 環形隊列類
  3. * 原作者 LKK/lianq.net
  4. * 修改 FoxHunter
  5. * 因業務需要只保留的隊列中的Pop和Push,修改到期時間為0即永久
  6. */
  7. class MQueue
  8. {
  9. public static $client;
  10. private $expire; //到期時間,秒,1~2592000,即30天內
  11. private $sleepTime; //等待解鎖時間,微秒
  12. private $queueName; //隊列名稱,唯一值
  13. private $retryNum; //嘗試次數
  14. private $MAXNUM; //最大隊列容量
  15. private $canRewrite; //是否可以覆寫開關,滿出來的內容從頭部開始覆蓋重寫原來的資料
  16. private $HEAD; //下一步要進入的指標位置
  17. private $TAIL; //下一步要進入的指標位置
  18. private $LEN; //隊列現有長度
  19. const LOCK_KEY = '_Fox_MQ_LOCK_'; //鎖儲存標示
  20. const LENGTH_KEY = '_Fox_MQ_LENGTH_'; //隊列現長度儲存標示
  21. const VALU_KEY = '_Fox_MQ_VAL_'; //隊列KVStore for Redis標示
  22. const HEAD_KEY = '_Fox_MQ_HEAD_'; //隊列HEAD指標位置標示
  23. const TAIL_KEY = '_Fox_MQ_TAIL_'; //隊列TAIL指標位置標示
  24. /*
  25. * 建構函式
  26. * 對於同一個$queueName,執行個體化時必須保障建構函式的參數值一致,否則pop和push會導隊列順序混亂
  27. */
  28. public function __construct($queueName = '', $maxqueue = 1, $canRewrite = false, $expire = 0, $config = '')
  29. {
  30. if (empty($config)) {
  31. self::$client = memcache_pconnect('127.0.0.1', 11211);
  32. } elseif (is_array($config)) { //array('host'=>'127.0.0.1','port'=>'11211')
  33. self::$client = memcache_pconnect($config['host'], $config['port']);
  34. } elseif (is_string($config)) { //"127.0.0.1:11211"
  35. $tmp = explode(':', $config);
  36. $conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0.0.1';
  37. $conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211';
  38. self::$client = memcache_pconnect($conf['host'], $conf['port']);
  39. }
  40. if (!self::$client)
  41. return false;
  42. ignore_user_abort(true); //當客戶中斷連線,允許繼續執行
  43. set_time_limit(0); //取消指令碼執行延時上限
  44. $this->access = false;
  45. $this->sleepTime = 1000;
  46. $expire = (empty($expire)) ? 0 : (int) $expire + 1;
  47. $this->expire = $expire;
  48. $this->queueName = $queueName;
  49. $this->retryNum = 20000;
  50. $this->MAXNUM = $maxqueue != null ? $maxqueue : 1;
  51. $this->canRewrite = $canRewrite;
  52. $this->getHeadAndTail();
  53. if (!isset($this->HEAD) || empty($this->HEAD))
  54. $this->HEAD = 0;
  55. if (!isset($this->TAIL) || empty($this->TAIL))
  56. $this->TAIL = 0;
  57. if (!isset($this->LEN) || empty($this->LEN))
  58. $this->LEN = 0;
  59. }
  60. //擷取隊列首尾指標資訊和長度
  61. private function getHeadAndTail()
  62. {
  63. $this->HEAD = (int) memcache_get(self::$client, $this->queueName . self::HEAD_KEY);
  64. $this->TAIL = (int) memcache_get(self::$client, $this->queueName . self::TAIL_KEY);
  65. $this->LEN = (int) memcache_get(self::$client, $this->queueName . self::LENGTH_KEY);
  66. }
  67. // 利用memcache_add原子性加鎖
  68. private function lock()
  69. {
  70. if ($this->access === false) {
  71. $i = 0;
  72. while (!memcache_add(self::$client, $this->queueName . self::LOCK_KEY, 1, false, $this->expire)) {
  73. usleep($this->sleepTime);
  74. @$i++;
  75. if ($i > $this->retryNum) { //嘗試等待N次
  76. return false;
  77. break;
  78. }
  79. }
  80. return $this->access = true;
  81. }
  82. return false;
  83. }
  84. //更新頭部指標指向,指向下一個位置
  85. private function incrHead()
  86. {
  87. //$this->getHeadAndTail(); //擷取最新指標資訊 ,由於本方法體均在鎖內調用,其鎖內已調用了此方法,本行注釋
  88. $this->HEAD++; //頭部指標下移
  89. if ($this->HEAD >= $this->MAXNUM) {
  90. $this->HEAD = 0; //邊界值修正
  91. }
  92. ;
  93. $this->LEN--; //Head的移動由Pop觸發,所以相當於數量減少
  94. if ($this->LEN < 0) {
  95. $this->LEN = 0; //邊界值修正
  96. }
  97. ;
  98. memcache_set(self::$client, $this->queueName . self::HEAD_KEY, $this->HEAD, false, $this->expire); //更新
  99. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新
  100. }
  101. //更新尾部指標指向,指向下一個位置
  102. private function incrTail()
  103. {
  104. //$this->getHeadAndTail(); //擷取最新指標資訊,由於本方法體均在鎖內調用,其鎖內已調用了此方法,本行注釋
  105. $this->TAIL++; //尾部指標下移
  106. if ($this->TAIL >= $this->MAXNUM) {
  107. $this->TAIL = 0; //邊界值修正
  108. }
  109. ;
  110. $this->LEN++; //Head的移動由Push觸發,所以相當於數量增加
  111. if ($this->LEN >= $this->MAXNUM) {
  112. $this->LEN = $this->MAXNUM; //邊界值長度修正
  113. }
  114. ;
  115. memcache_set(self::$client, $this->queueName . self::TAIL_KEY, $this->TAIL, false, $this->expire); //更新
  116. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新
  117. }
  118. // 解鎖
  119. private function unLock()
  120. {
  121. memcache_delete(self::$client, $this->queueName . self::LOCK_KEY);
  122. $this->access = false;
  123. }
  124. //判斷是否滿隊列
  125. public function isFull()
  126. {
  127. //外部直接調用的時候由於沒有鎖所以此處的值是個大概值,並不很準確,但是內部調用由於在前面有lock,所以可信
  128. if ($this->canRewrite)
  129. return false;
  130. return $this->LEN == $this->MAXNUM ? true : false;
  131. }
  132. //判斷是否為空白
  133. public function isEmpty()
  134. {
  135. //外部直接調用的時候由於沒有鎖所以此處的值是個大概值,並不很準確,但是內部調用由於在前面有lock,所以可信
  136. return $this->LEN == 0 ? true : false;
  137. }
  138. public function getLen()
  139. {
  140. //外部直接調用的時候由於沒有鎖所以此處的值是個大概值,並不很準確,但是內部調用由於在前面有lock,所以可信
  141. return $this->LEN;
  142. }
  143. /*
  144. * push值
  145. * @param mixed 值
  146. * @return bool
  147. */
  148. public function push($data = '')
  149. {
  150. $result = false;
  151. if (empty($data))
  152. return $result;
  153. if (!$this->lock()) {
  154. return $result;
  155. }
  156. $this->getHeadAndTail(); //擷取最新指標資訊
  157. if ($this->isFull()) { //只有在非覆寫下才有Full概念
  158. $this->unLock();
  159. return false;
  160. }
  161. if (memcache_set(self::$client, $this->queueName . self::VALU_KEY . $this->TAIL, $data, MEMCACHE_COMPRESSED, $this->expire)) {
  162. //當推送後,發現尾部和頭部重合(此時指標還未移動),且右邊仍有未由Head讀取的資料,那麼移動Head指標,避免尾部指標跨越Head
  163. if ($this->TAIL == $this->HEAD && $this->LEN >= 1) {
  164. $this->incrHead();
  165. }
  166. $this->incrTail(); //移動尾部指標
  167. $result = true;
  168. }
  169. $this->unLock();
  170. return $result;
  171. }
  172. /*
  173. * Pop一個值
  174. * @param [length] int 隊列長度
  175. * @return array
  176. */
  177. public function pop($length = 0)
  178. {
  179. if (!is_numeric($length))
  180. return false;
  181. if (!$this->lock())
  182. return false;
  183. $this->getHeadAndTail();
  184. if (empty($length))
  185. $length = $this->LEN; //預設讀取所有
  186. if ($this->isEmpty()) {
  187. $this->unLock();
  188. return false;
  189. }
  190. //擷取長度超出隊列長度後進行修正
  191. if ($length > $this->LEN)
  192. $length = $this->LEN;
  193. $data = $this->popKeyArray($length);
  194. $this->unLock();
  195. return $data;
  196. }
  197. /*
  198. * pop某段長度的值
  199. * @param [length] int 隊列長度
  200. * @return array
  201. */
  202. private function popKeyArray($length)
  203. {
  204. $result = array();
  205. if (empty($length))
  206. return $result;
  207. for ($k = 0; $k < $length; $k++) {
  208. $result[] = @memcache_get(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD);
  209. @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD, 0);
  210. //當提取值後,發現頭部和尾部重合(此時指標還未移動),且右邊沒有資料,即隊列中最後一個資料被完全掏空,此時指標停留在本地不移動,隊列長度變為0
  211. if ($this->TAIL == $this->HEAD && $this->LEN <= 1) {
  212. $this->LEN = 0;
  213. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //更新
  214. break;
  215. } else {
  216. $this->incrHead(); //首尾未重合,或者重合但是仍有未讀取出的資料,均移動HEAD指標到下一處待讀取位置
  217. }
  218. }
  219. return $result;
  220. }
  221. /*
  222. * 重設隊列
  223. * * @return NULL
  224. */
  225. private function reset($all = false)
  226. {
  227. if ($all) {
  228. memcache_delete(self::$client, $this->queueName . self::HEAD_KEY, 0);
  229. memcache_delete(self::$client, $this->queueName . self::TAIL_KEY, 0);
  230. memcache_delete(self::$client, $this->queueName . self::LENGTH_KEY, 0);
  231. } else {
  232. $this->HEAD = $this->TAIL = $this->LEN = 0;
  233. memcache_set(self::$client, $this->queueName . self::HEAD_KEY, 0, false, $this->expire);
  234. memcache_set(self::$client, $this->queueName . self::TAIL_KEY, 0, false, $this->expire);
  235. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, 0, false, $this->expire);
  236. }
  237. }
  238. /*
  239. * 清除所有memcache快取資料
  240. * @return NULL
  241. */
  242. public function memFlush()
  243. {
  244. memcache_flush(self::$client);
  245. }
  246. public function clear($all = false)
  247. {
  248. if (!$this->lock())
  249. return false;
  250. $this->getHeadAndTail();
  251. $Head = $this->HEAD;
  252. $Length = $this->LEN;
  253. $curr = 0;
  254. for ($i = 0; $i < $Length; $i++) {
  255. $curr = $this->$Head + $i;
  256. if ($curr >= $this->MAXNUM) {
  257. $this->HEAD = $curr = 0;
  258. }
  259. @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $curr, 0);
  260. }
  261. $this->unLock();
  262. $this->reset($all);
  263. return true;
  264. }
  265. }
複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.