Home Backend Development PHP Tutorial PHP memcache ring queue

PHP memcache ring queue

Jul 25, 2016 am 08:48 AM

PHP memcache ring queue class. I'm a newbie and haven't learned much about data structures. Because of business needs, I just simulated it! The prototype is the PHP memcache queue code shared by lusi on oschina. In order to ensure that the queue can be entered and exited at any time without the danger of the int length crossing the boundary (if the single chain adopts Head auto-increment, there is a possibility of crossing the boundary without processing), so it is simply rewritten into a circular queue.There may be bugs, sorry!
  1. /**
  2. * PHP memcache ring queue class
  3. * Original author LKK/lianq.net
  4. * Modified FoxHunter
  5. * Due to business needs, only the Pop and Push in the queue are retained. Modify the expiration time to 0, which is permanent
  6. */
  7. class MQueue
  8. {
  9. public static $client;
  10. private $expire; //Expiration time, seconds, 1~2592000, that is, within 30 days
  11. private $sleepTime; //Waiting time to unlock, microseconds
  12. private $queueName; //Queue name, unique value
  13. private $retryNum; //Number of attempts
  14. private $MAXNUM; //Maximum queue capacity
  15. private $canRewrite; // Is it possible to overwrite the switch, and the full content will overwrite the original data from the head
  16. private $HEAD; //The pointer position to be entered in the next step
  17. private $TAIL; //The pointer position to be entered in the next step
  18. private $LEN; //The current length of the queue
  19. const LOCK_KEY = '_Fox_MQ_LOCK_'; //Lock storage indicator
  20. const LENGTH_KEY = '_Fox_MQ_LENGTH_'; //The current length storage indicator of the queue
  21. const VALU_KEY = '_Fox_MQ_VAL_'; //Queue Key-value storage indicator
  22. const HEAD_KEY = '_Fox_MQ_HEAD_'; // Queue HEAD pointer location indicator
  23. const TAIL_KEY = '_Fox_MQ_TAIL_'; // Queue TAIL pointer location indicator
  24. /*
  25. * Constructor
  26. * For the same $queueName, When instantiating, you must ensure that the parameter values ​​of the constructor are consistent, otherwise pop and push will cause confusion in the queue order
  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); //When the client disconnects, allow execution to continue
  43. set_time_limit(0); //Cancel the upper limit of script execution delay
  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. //Get the head and tail pointer information and length of the queue
  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. // Use memcache_add atomic lock
  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) { //Try to wait N times
  76. return false;
  77. break;
  78. }
  79. }
  80. return $this->access = true;
  81. }
  82. return false;
  83. }
  84. / /Update the head pointer to point to the next position
  85. private function incrHead()
  86. {
  87. //$this->getHeadAndTail(); //Get the latest pointer information, since this method body is called within the lock, its lock This method has been called, this line comment
  88. $this->HEAD++; //Move the head pointer down
  89. if ($this->HEAD >= $this->MAXNUM) {
  90. $this-> ;HEAD = 0; //Boundary value correction
  91. }
  92. ;
  93. $this->LEN--; //The movement of Head is triggered by Pop, so it is equivalent to a reduction in quantity
  94. if ($this->LEN < 0) {
  95. $this->LEN = 0; //Boundary value correction
  96. }
  97. ;
  98. memcache_set(self::$client, $this->queueName . self::HEAD_KEY, $this->HEAD, false, $this->expire); //Update
  99. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //Update
  100. }
  101. //Update the tail The pointer points to the next position
  102. private function incrTail()
  103. {
  104. //$this->getHeadAndTail(); //Get the latest pointer information, since this method body is called within the lock, it has been called within the lock For this method, comment this line
  105. $this->TAIL++; //Move the tail pointer down
  106. if ($this->TAIL >= $this->MAXNUM) {
  107. $this->TAIL = 0 ; //Boundary value correction
  108. }
  109. ;
  110. $this->LEN++; //Head’s movement is triggered by Push, so it is equivalent to an increase in quantity
  111. if ($this->LEN >= $this->MAXNUM ) {
  112. $this->LEN = $this->MAXNUM; //Boundary value length correction
  113. }
  114. ;
  115. memcache_set(self::$client, $this->queueName . self::TAIL_KEY, $this ->TAIL, false, $this->expire); //Update
  116. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this ->expire); //Update
  117. }
  118. //Unlock
  119. private function unLock()
  120. {
  121. memcache_delete(self::$client, $this->queueName . self::LOCK_KEY);
  122. $this ->access = false;
  123. }
  124. //Determine whether the queue is full
  125. public function isFull()
  126. {
  127. //When called directly from the outside, there is no lock, so the value here is an approximate value and not very accurate. But the internal call is credible because there is a lock in front of it
  128. if ($this->canRewrite)
  129. return false;
  130. return $this->LEN == $this->MAXNUM ? true : false;
  131. }
  132. //Judge whether it is empty
  133. public function isEmpty()
  134. {
  135. //When called directly from the outside, since there is no lock, the value here is an approximate value and not very accurate. However, because there is a lock in front of the internal call, so Trusted
  136. return $this->LEN == 0 ? true : false;
  137. }
  138. public function getLen()
  139. {
  140. //When called directly from the outside, there is no lock, so the value here is an approximate value, and Not very accurate, but the internal call has a lock in front, so it is credible
  141. return $this->LEN;
  142. }
  143. /*
  144. * push value
  145. * @param mixed value
  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(); //Get the latest pointer information
  157. if ($this->isFull()) { //The Full concept is only available under non-overwriting
  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. //After pushing, it is found that the tail and the head overlap (the pointer has not moved yet), and there is still data on the right that has not been read by the Head, then move the Head pointer to avoid the tail Pointer spans Head
  163. if ($this->TAIL == $this->HEAD && $this->LEN >= 1) {
  164. $this->incrHead();
  165. }
  166. $this-> ;incrTail(); //Move the tail pointer
  167. $result = true;
  168. }
  169. $this->unLock();
  170. return $result;
  171. }
  172. /*
  173. * Pop a value
  174. * @param [length] int queue length
  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; //Read all by default
  186. if ( $this->isEmpty()) {
  187. $this->unLock();
  188. return false;
  189. }
  190. //Correction after the length exceeds the queue length
  191. if ($length > $this->LEN )
  192. $length = $this->LEN;
  193. $data = $this->popKeyArray($length);
  194. $this->unLock();
  195. return $data;
  196. }
  197. /*
  198. * pop the value of a certain length
  199. * @param [length] int queue length
  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. //After extracting the value, it is found that the head and tail overlap (the pointer has not moved at this time), and there is no data on the right, that is, the last data in the queue is completely emptied. At this time, the pointer stays local and does not move. The queue length becomes 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); //Update
  214. break;
  215. } else {
  216. $this->incrHead() ; //The head and tail do not overlap, or they overlap but there is still unread data, move the HEAD pointer to the next position to be read
  217. }
  218. }
  219. return $result;
  220. }
  221. /*
  222. * Reset Queue
  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. * Clear all memcache cache data
  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. }
Copy code


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

See all articles