Home > Backend Development > PHP Tutorial > PHP memcache ring queue

PHP memcache ring queue

WBOY
Release: 2016-07-25 08:48:25
Original
1068 people have browsed it
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


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template