PHP's Memcache class sharing

Source: Internet
Author: User
Tags bool config

  This article mainly introduces the use of PHP Memcache class (Memcache queue), the need for friends can refer to the following

memcachequeue.class.php    Code is as follows: <?php/**  * php memcache Queue class  * @author lkk/lianq.net  * @ve Rsion 0.3  * @ modification Note:  * 1. The previous AB rotation was discarded and the class was rewritten using an array-like construct.  * 2. The queue defaults to FIFO, but it adds a reverse read function.  * 3. Thanks to netizens foxhunter for their valuable advice.  * @example:  * $obj = new Memcachequeue (' Duilie ');  * $obj->add (' 1asdf ');  * $obj->getqueuelength ();  * $obj->read (10);  * $obj->get (8);  */class memcachequeue{ public static $client  //memcache Client connection  public   $access;  //queue Whether  private   $expire can be updated;  //Expiration time, seconds, 1~2592000, that is, within 30 days  private   $sleepTime;  /Waiting for unlock time, microsecond  private   $queueName;  //queue name, unique value  private   $retryNum;  //retry times, = 10 * Theoretical concurrency number  public   $currentHead;  //Current team first value  public   $currentTail;  //Current team tail value    const maxnum  = 20000;    //Maximum number of queues, recommended cap 10K  const head_key = ' _lkkqueuehead_ ';  //queuesThe first kye  const tail_key = ' _lkkqueuetail_ ';  //Queue Tail KEY  const valu_key = ' _lkkqueuevalu_ ';  //Queue value KEY  const lock_key = ' _lkkqueuelock_ ';  //Queue lock key      /**      * constructor      * @param string $queueName   queue Name      * @param int $expire expiration      * @param array $config  memcache configuration      *       * @return <type>      */ public function __construct ($queueN Ame = ', $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 customer disconnects, allow execution of   set_time_limit (0);//Cancel Script Execution Latency limit     $this-> Access = false;   $this->sleeptime = 1000;   $expire = Empty ($expire)? 3600:intval ($expire) +1;   $this->expire = $expire;   $this->queuename = $queueName;   $this->retrynum = 1000;     $this->head_key = $this->queuename. Self::head_key;   $this->tail_key = $this->queuename. Self::tail_key;   $this->lock_key = $this->queuename. Self::lock_key;     $this->_initsetheadntail (); &NBSP}      /**      * initialization set queue end value      */ private function _initsethe Adntail () { //current queue first value   $this->currenthead = Memcache_get (self:: $client, $this->head_key);   IF ($this->currenthead = false) $this->currenthead = 0;    //Current queue tail value   $this->currenttail = Memcache_get (self:: $client, $this->tail_key);   if ($this->currenttail = false) $this->currenttail = 0; &NBSP}      /**      * When the element is taken out, change the value of the queue first   * @param int $step step value      * / private function _changehead ($step =1) {  $this->currenthead + = $step;   Memcache_set (self:: $client , $this->head_key, $this->currenthead,false, $this->expire); &NBSP}      /**      * When adding elements, change the value of the queue at the end of   * @param int $step step value      * @param bool $reverse reverse      * @return null      */ private function _changetail ($s Tep=1, $reverse =false) {  if (! $reverse) {    $this->currenttail + = $step;  }else{    $th Is->currenttail-= $step;  }     Memcache_set (self:: $client, $this->Tail_key, $this->currenttail,false, $this->expire); &NBSP}      /**      * queue null      * @return bool      */&N bsp;private function _isempty () {  return (bool) ($this->currenthead = = $this->currenttail);  }   & nbsp  /**      * queue is full      * @return bool      */ private Function _ Isfull () {  $len = $this->currenttail-$this->currenthead;   return (bool) ($len = = Self::maxnum);   }      /**      * queue lock      */ private function _getlock () {  if ( $this->access = = False) {   while!memcache_add (self:: $client, $this->lock_key, 1, false, $this-> Expire) {    usleep ($this->sleeptime)     @ $i + +     if ($i > $this->retrynum) {// Try to wait n times      return false;      break;    }  &NBSP}       $this->_initsetheadntail ();    return $this->access = true;       return $this->access; &NBSP}      /**      * queue unlock      */ private function _unlock () {&nbsp ; Memcache_delete (self:: $client, $this->lock_key, 0);   $this->access = false; &NBSP}      /**      * Get the length of the current queue      * The length is theoretical length, some elements are lost due to expiration, the true length <= the length      * @return int      */ public function getqueuelength () {  $this->_initse Theadntail ();   Return intval ($this->currenttail-$this->currenthead); &NBSP}      /**      * add queue data      * @param void $data data to add      * @return bool      */ public function Add ($data) {  if (! $this->_getlock ()) return FAL Se     if ($this->_isfull ()) {    $this; _unlock ();    return false;  }     $value _key = $this->queuename. Self::valu_key. Strval ($this->currenttail + 1);   $result = Memcache_set (self:: $client, $value _key, $data, memcache_compressed, $this->expire);   if ($result) {    $this->_changetail ()  }     $this->_unlock ();   return $result; &NBSP}      /**      * read queue data      * @param int $length The length to read (negative read used) &N Bsp    * @return Array      */ public function read ($length =0) {  if (!is_numeric ($length) ) return false;   $this->_initsetheadntail ();     if ($this->_isempty ()) {   return false;  }     if (empty ($length)) $length = Sel f::maxnum;//default all   $KEYARR = Array ();   if ($length >0) {//forward read (from queue header end)     $tmpMin = $this->currenthead;     $tmpMax = $tmpMin + $ Length    for ($i = $tmpMIn; $i <= $tmpMax; $i + +) {    $KEYARR [] = $this->queuename. Self::valu_key. $i;      }else{//Reverse read (from the end of the queue to the head of the queue) & nbsp   $tmpMax = $this->currenttail;     $tmpMin = $tmpMax + $length;    for ($i = $tmpMax; $i > $tmpMin; $i-) {    $KEYARR [] = $this->queuename. Self::valu_key. $i;   &NBSP}       $result = @memcache_get (self:: $client, $KEYARR);     return $result; &NBSP}      /**      * take out queue data      * @param int $length length to be fetched (negative read use minus) &N Bsp    * @return Array      */ public function get ($length =0) {  if (!is_numeric ($length)) return false;   if (! $this->_getlock ()) return false;     if ($this->_isempty ()) {    $this->_unlock ();    return false;  }   &nbs P if (empty ($length)) $length = self::maxnum;//default all   $length = Intval ($length);   $KEYARR= Array ();   if ($length >0) {//forward read (from queue header end)     $tmpMin = $this->currenthead;     $tmpMax = $tmpMin + $ Length    for ($i = $tmpMin; $i <= $tmpMax; $i + +) {    $KEYARR [] = $this->queuename. Self::valu_key. $i;   &nbsp     $this->_changehead ($length);  }else{//Reverse read (from queue end to queue head)     $tmpMax = $this->currenttail;     $tmpMin = $tmpMax + $length; &nbs P  for ($i = $tmpMax; $i > $tmpMin; $i-) {    $KEYARR [] = $this->queuename. Self::valu_key. $i;   &NBSP}     $this->_changetail (ABS ($length), true);  }   $result = @memcache_get (self:: $client, $KEYARR);     foreach ($keyArr as $v) {//delete after removal     @memcache_delete (self:: $client, $v, 0);  }     $this->_unlock ();     return $result; &NBSP}      /**      * emptying queue      */ public function Clear () {  I F (! $thIs->_getlock ()) return false;     if ($this->_isempty ()) {    $this->_unlock ();    return false;  }   &nbs P $tmpMin = $this->currenthead--;   $tmpMax = $this->currenttail++;     for ($i = $tmpMin $i <= $tmpMax $i + +) {    $tmpKey = $this->queuename. Self::valu_key $i; &n Bsp   @memcache_delete (self:: $client, $tmpKey, 0);  }     $this->currenttail = $this->currenthead = 0;   Memcache_set (self:: $client, $this->head_key, $this->currenthead,false, $this->expire);   Memcache_set (self:: $client, $this->tail_key, $this->currenttail,false, $this->expire);     $this->_unlock (); &NBSP}    /*   * Clear all memcache cache data  / public function Memflush () {  Memcache_flush (self:: $client); &NBSP}  }//end class  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.