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!
- /**
- * PHP memcache ring queue class
- * Original author LKK/lianq.net
- * Modified FoxHunter
- * Due to business needs, only the Pop and Push in the queue are retained. Modify the expiration time to 0, which is permanent
- */
- class MQueue
- {
- public static $client;
-
- private $expire; //Expiration time, seconds, 1~2592000, that is, within 30 days
- private $sleepTime; //Waiting time to unlock, microseconds
- private $queueName; //Queue name, unique value
- private $retryNum; //Number of attempts
- private $MAXNUM; //Maximum queue capacity
- private $canRewrite; // Is it possible to overwrite the switch, and the full content will overwrite the original data from the head
-
- private $HEAD; //The pointer position to be entered in the next step
- private $TAIL; //The pointer position to be entered in the next step
- private $LEN; //The current length of the queue
-
- const LOCK_KEY = '_Fox_MQ_LOCK_'; //Lock storage indicator
- const LENGTH_KEY = '_Fox_MQ_LENGTH_'; //The current length storage indicator of the queue
- const VALU_KEY = '_Fox_MQ_VAL_'; //Queue Key-value storage indicator
- const HEAD_KEY = '_Fox_MQ_HEAD_'; // Queue HEAD pointer location indicator
- const TAIL_KEY = '_Fox_MQ_TAIL_'; // Queue TAIL pointer location indicator
-
- /*
- * Constructor
- * 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
- */
- public function __construct($queueName = '', $maxqueue = 1, $canRewrite = false, $expire = 0, $config = '')
- {
- if (empty($config)) {
- self::$client = memcache_pconnect('127.0.0.1', 11211);
- } elseif (is_array($config)) { //array ('host'=>'127.0.0.1','port'=>'11211')
- self::$client = memcache_pconnect($config['host'], $config['port']);
- } elseif (is_string($config)) { //"127.0.0.1:11211"
- $tmp = explode(':', $config);
- $conf['host'] = isset($tmp[0]) ? $tmp[0] : '127.0.0.1';
- $conf['port'] = isset($tmp[1]) ? $tmp[1] : '11211';
- self::$client = memcache_pconnect( $conf['host'], $conf['port']);
- }
- if (!self::$client)
- return false;
- ignore_user_abort(true); //When the client disconnects, allow execution to continue
- set_time_limit(0); //Cancel the upper limit of script execution delay
- $this->access = false;
- $this->sleepTime = 1000;
- $expire = (empty($expire)) ? 0 : (int ) $expire + 1;
- $this->expire = $expire;
- $this->queueName = $queueName;
- $this->retryNum = 20000;
- $this->MAXNUM = $maxqueue != null ? $maxqueue : 1;
- $this->canRewrite = $canRewrite;
- $this->getHeadAndTail();
- if (!isset($this->HEAD) || empty($this-> HEAD))
- $this->HEAD = 0;
- if (!isset($this->TAIL) || empty($this->TAIL))
- $this->TAIL = 0;
- if (!isset($this->LEN) || empty($this->LEN))
- $this->LEN = 0;
-
- }
-
- //Get the head and tail pointer information and length of the queue
- private function getHeadAndTail()
- {
- $this->HEAD = (int) memcache_get(self::$client, $this->queueName . self::HEAD_KEY);
- $this->TAIL = (int) memcache_get( self::$client, $this->queueName . self::TAIL_KEY);
- $this->LEN = (int) memcache_get(self::$client, $this->queueName . self::LENGTH_KEY) ;
- }
-
-
- // Use memcache_add atomic lock
- private function lock()
- {
- if ($this->access === false) {
- $i = 0;
- while (!memcache_add(self ::$client, $this->queueName . self::LOCK_KEY, 1, false, $this->expire)) {
- usleep($this->sleepTime);
- @$i++;
- if ($ i > $this->retryNum) { //Try to wait N times
- return false;
- break;
- }
- }
- return $this->access = true;
- }
- return false;
- }
-
- / /Update the head pointer to point to the next position
- private function incrHead()
- {
- //$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
- $this->HEAD++; //Move the head pointer down
- if ($this->HEAD >= $this->MAXNUM) {
- $this-> ;HEAD = 0; //Boundary value correction
- }
- ;
- $this->LEN--; //The movement of Head is triggered by Pop, so it is equivalent to a reduction in quantity
- if ($this->LEN < 0) {
- $this->LEN = 0; //Boundary value correction
- }
- ;
- memcache_set(self::$client, $this->queueName . self::HEAD_KEY, $this->HEAD, false, $this->expire); //Update
- memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //Update
-
- }
-
- //Update the tail The pointer points to the next position
- private function incrTail()
- {
-
- //$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
- $this->TAIL++; //Move the tail pointer down
- if ($this->TAIL >= $this->MAXNUM) {
- $this->TAIL = 0 ; //Boundary value correction
- }
- ;
- $this->LEN++; //Head’s movement is triggered by Push, so it is equivalent to an increase in quantity
- if ($this->LEN >= $this->MAXNUM ) {
- $this->LEN = $this->MAXNUM; //Boundary value length correction
- }
- ;
- memcache_set(self::$client, $this->queueName . self::TAIL_KEY, $this ->TAIL, false, $this->expire); //Update
- memcache_set(self::$client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this ->expire); //Update
- }
-
-
- //Unlock
- private function unLock()
- {
- memcache_delete(self::$client, $this->queueName . self::LOCK_KEY);
- $this ->access = false;
- }
-
- //Determine whether the queue is full
- public function isFull()
- {
- //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
- if ($this->canRewrite)
- return false;
- return $this->LEN == $this->MAXNUM ? true : false;
- }
-
- //Judge whether it is empty
- public function isEmpty()
- {
- //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
- return $this->LEN == 0 ? true : false;
- }
-
- public function getLen()
- {
- //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
- return $this->LEN;
- }
-
- /*
- * push value
- * @param mixed value
- * @return bool
- */
- public function push($data = '')
- {
-
- $result = false;
- if (empty($data))
- return $result;
-
- if (!$this->lock()) {
- return $result;
- }
-
- $this->getHeadAndTail(); //Get the latest pointer information
-
- if ($this->isFull()) { //The Full concept is only available under non-overwriting
- $ this->unLock();
- return false;
- }
-
- if (memcache_set(self::$client, $this->queueName . self::VALU_KEY . $this->TAIL, $data, MEMCACHE_COMPRESSED, $this->expire)) {
- //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
- if ($this->TAIL == $this->HEAD && $this->LEN >= 1) {
- $this->incrHead();
- }
- $this-> ;incrTail(); //Move the tail pointer
- $result = true;
- }
-
- $this->unLock();
- return $result;
- }
-
-
- /*
- * Pop a value
- * @param [length] int queue length
- * @return array
- */
- public function pop($length = 0)
- {
- if (!is_numeric($length))
- return false;
-
- if (!$this-> lock())
- return false;
-
- $this->getHeadAndTail();
-
- if (empty($length))
- $length = $this->LEN; //Read all by default
-
- if ( $this->isEmpty()) {
- $this->unLock();
- return false;
- }
- //Correction after the length exceeds the queue length
- if ($length > $this->LEN )
- $length = $this->LEN;
-
- $data = $this->popKeyArray($length);
- $this->unLock();
- return $data;
- }
-
-
- /*
- * pop the value of a certain length
- * @param [length] int queue length
- * @return array
- */
- private function popKeyArray($length)
- {
-
- $result = array();
- if (empty($length))
- return $result;
- for ($k = 0; $k < $length; $k++) {
- $result[] = @memcache_get(self::$client, $this ->queueName . self::VALU_KEY . $this->HEAD);
- @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $this->HEAD, 0);
- //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
- if ($this->TAIL == $this->HEAD && $this->LEN <= 1) {
- $this->LEN = 0;
- memcache_set(self::$ client, $this->queueName . self::LENGTH_KEY, $this->LEN, false, $this->expire); //Update
- break;
- } else {
- $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
- }
- }
- return $result;
- }
-
- /*
- * Reset Queue
- * * @return NULL
- */
- private function reset($all = false)
- {
-
- if ($all) {
- memcache_delete(self::$client, $this->queueName . self::HEAD_KEY , 0);
- memcache_delete(self::$client, $this->queueName . self::TAIL_KEY, 0);
- memcache_delete(self::$client, $this->queueName . self::LENGTH_KEY, 0 );
- } else {
- $this->HEAD = $this->TAIL = $this->LEN = 0;
- memcache_set(self::$client, $this->queueName . self::HEAD_KEY , 0, false, $this->expire);
- memcache_set(self::$client, $this->queueName . self::TAIL_KEY, 0, false, $this->expire);
- memcache_set(self ::$client, $this->queueName . self::LENGTH_KEY, 0, false, $this->expire);
- }
- }
-
- /*
- * Clear all memcache cache data
- * @return NULL
- */
- public function memFlush()
- {
- memcache_flush(self::$client);
- }
-
-
- public function clear($all = false)
- {
- if (!$this->lock())
- return false;
- $this->getHeadAndTail();
- $Head = $this->HEAD;
- $Length = $this->LEN;
- $curr = 0;
- for ($i = 0; $ i < $Length; $i++) {
- $curr = $this->$Head + $i;
- if ($curr >= $this->MAXNUM) {
- $this->HEAD = $ curr = 0;
- }
- @memcache_delete(self::$client, $this->queueName . self::VALU_KEY . $curr, 0);
- }
-
-
- $this->unLock();
- $ this->reset($all);
- return true;
- }
-
-
- }
Copy code
|