search

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 $this->LEN = 0; //Boundary value correction
  95. }
  96. ;
  97. memcache_set(self::$client, $this->queueName . self::HEAD_KEY, $this->HEAD, false, $this->expire); //Update
  98. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //Update
  99. }
  100. //Update the tail The pointer points to the next position
  101. private function incrTail()
  102. {
  103. //$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
  104. $this->TAIL++; //Move the tail pointer down
  105. if ($this->TAIL >= $this->MAXNUM) {
  106. $this->TAIL = 0 ; //Boundary value correction
  107. }
  108. ;
  109. $this->LEN++; //Head’s movement is triggered by Push, so it is equivalent to an increase in quantity
  110. if ($this->LEN >= $this->MAXNUM ) {
  111. $this->LEN = $this->MAXNUM; //Boundary value length correction
  112. }
  113. ;
  114. memcache_set(self::$client, $this->queueName . self::TAIL_KEY, $this ->TAIL, false, $this->expire); //Update
  115. memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this ->expire); //Update
  116. }
  117. //Unlock
  118. private function unLock()
  119. {
  120. memcache_delete(self::$client, $this->queueName . self::LOCK_KEY);
  121. $this ->access = false;
  122. }
  123. //Determine whether the queue is full
  124. public function isFull()
  125. {
  126. //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
  127. if ($this->canRewrite)
  128. return false;
  129. return $this->LEN == $this->MAXNUM ? true : false;
  130. }
  131. //Judge whether it is empty
  132. public function isEmpty()
  133. {
  134. //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
  135. return $this->LEN == 0 ? true : false;
  136. }
  137. public function getLen()
  138. {
  139. //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
  140. return $this->LEN;
  141. }
  142. /*
  143. * push value
  144. * @param mixed value
  145. * @return bool
  146. */
  147. public function push($data = '')
  148. {
  149. $result = false;
  150. if (empty($data))
  151. return $result;
  152. if (!$this->lock()) {
  153. return $result;
  154. }
  155. $this->getHeadAndTail(); //Get the latest pointer information
  156. if ($this->isFull()) { //The Full concept is only available under non-overwriting
  157. $ this->unLock();
  158. return false;
  159. }
  160. if (memcache_set(self::$client, $this->queueName . self::VALU_KEY . $this->TAIL, $data, MEMCACHE_COMPRESSED, $this->expire)) {
  161. //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
  162. if ($this->TAIL == $this->HEAD && $this->LEN >= 1) {
  163. $this->incrHead();
  164. }
  165. $this-> ;incrTail(); //Move the tail pointer
  166. $result = true;
  167. }
  168. $this->unLock();
  169. return $result;
  170. }
  171. /*
  172. * Pop a value
  173. * @param [length] int queue length
  174. * @return array
  175. */
  176. public function pop($length = 0)
  177. {
  178. if (!is_numeric($length))
  179. return false;
  180. if (!$this-> lock())
  181. return false;
  182. $this->getHeadAndTail();
  183. if (empty($length))
  184. $length = $this->LEN; //Read all by default
  185. if ( $this->isEmpty()) {
  186. $this->unLock();
  187. return false;
  188. }
  189. //Correction after the length exceeds the queue length
  190. if ($length > $this->LEN )
  191. $length = $this->LEN;
  192. $data = $this->popKeyArray($length);
  193. $this->unLock();
  194. return $data;
  195. }
  196. /*
  197. * pop the value of a certain length
  198. * @param [length] int queue length
  199. * @return array
  200. */
  201. private function popKeyArray($length)
  202. {
  203. $result = array();
  204. if (empty($length))
  205. return $result;
  206. for ($k = 0; $k $result[] = @memcache_get(self::$client, $this ->queueName . self::VALU_KEY . $this->HEAD);
  207. @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD, 0);
  208. //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
  209. if ($this->TAIL == $this->HEAD && $this->LEN $this->LEN = 0;
  210. memcache_set(self::$ client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //Update
  211. break;
  212. } else {
  213. $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
  214. }
  215. }
  216. return $result;
  217. }
  218. /*
  219. * Reset Queue
  220. * * @return NULL
  221. */
  222. private function reset($all = false)
  223. {
  224. if ($all) {
  225. memcache_delete(self::$client, $this->queueName . self::HEAD_KEY , 0);
  226. memcache_delete(self::$client, $this->queueName . self::TAIL_KEY, 0);
  227. memcache_delete(self::$client, $this->queueName . self::LENGTH_KEY, 0 );
  228. } else {
  229. $this->HEAD = $this->TAIL = $this->LEN = 0;
  230. memcache_set(self::$client, $this->queueName . self::HEAD_KEY , 0, false, $this->expire);
  231. memcache_set(self::$client, $this->queueName . self::TAIL_KEY, 0, false, $this->expire);
  232. memcache_set(self ::$client, $this->queueName . self::LENGTH_KEY, 0, false, $this->expire);
  233. }
  234. }
  235. /*
  236. * Clear all memcache cache data
  237. * @return NULL
  238. */
  239. public function memFlush()
  240. {
  241. memcache_flush(self::$client);
  242. }
  243. public function clear($all = false)
  244. {
  245. if (!$this->lock())
  246. return false;
  247. $this->getHeadAndTail();
  248. $Head = $this->HEAD;
  249. $Length = $this->LEN;
  250. $curr = 0;
  251. for ($i = 0; $ i $curr = $this->$Head + $i;
  252. if ($curr >= $this->MAXNUM) {
  253. $this->HEAD = $ curr = 0;
  254. }
  255. @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $curr, 0);
  256. }
  257. $this->unLock();
  258. $ this->reset($all);
  259. return true;
  260. }
  261. }
Copy code


Statement
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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools