PHP self-implemented memcached queue class _php tutorial

Source: Internet
Author: User

PHP itself implements the Memcached queue class


 Add (' 1asdf '); * $obj->getqueuelength (); * $obj->read (11); * $obj->get (8);            */class memcachequeue{public static $client;            Memcache Client connection to public $access;       Whether the queue can update private $currentSide;          Current rotating queue face: A/b private $lastSide;         Last rotated queue face: A/b private $sideAHead;         A side team first value private $sideATail;         A side team tail value private $sideBHead;         B-side team first value private $sideBTail;       B-side Team tail value private $currentHead;       The current team first value private $currentTail;          The current team tail value private $lastHead;          The first round of the team's private $lastTail;            The tail value of the team is private $expire;         Expiration time, seconds, 1~2592000, i.e. within 30 days; 0 for never expire private $sleepTime;         Wait for unlock time, microsecond private $queueName;          Queue name, unique value private $retryNum;                 Number of retries, = 10 * Theoretical concurrency number const MAXNUM = 2000; (single side) Most brigadeNumber of columns, recommended upper 10K const Head_key = ' _lkkqueuehead_ ';     Queue First Kye const Tail_key = ' _lkkqueuetail_ ';     Queue tail KEY Const Valu_key = ' _lkkqueuevalu_ ';     Queue value KEY Const Lock_key = ' _lkkqueuelock_ ';     Queue lock KEY Const Side_key = ' _lkkqueueside_ '; Rotating Surface Key/* constructor * @param [Config] array memcache server parameter * @param [queuename] string queue name * @ param [expire] string expiration time * @return NULL */Public function __construct ($queueName = ", $expire =", $conf        IG = ') {if (empty ($config)) {self:: $client = memcache_pconnect (' localhost ', 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 to continue execution of Set_time_limit (0);//Cancel Script execution delay limit $this->access = false;        $this->sleeptime = 1000; $expire = (Empty ($expire) && $expire!=0)?        3600: (int) $expire;        $this->expire = $expire;        $this->queuename = $queueName;        $this->retrynum = 10000;        $side = Memcache_add (self:: $client, $queueName. Self::side_key, ' A ', false, $expire);        $this->getheadntail ($queueName);        if (!isset ($this->sideahead) | | empty ($this->sideahead)) $this->sideahead = 0;        if (!isset ($this->sideatail) | | empty ($this->sideatail)) $this->sideatail = 0;        if (!isset ($this->sidebhead) | | empty ($this->sidebhead)) $this->sidebhead = 0; if (!isset ($this->sidebhead) | | empty ($this->sidebhead)) $this->sidebhead = 0;    }/* * Get queue end and end values * @param [queuename] string queue name * @return NULL */Private Function getheadnt        AIL ($queueName) {$this->sideahead = (int) memcache_get (self:: $client, $queueName. ' A '. Self::head_key);        $this->sideatail = (int) memcache_get (self:: $client, $queueName. ' A '. Self::tail_key);        $this->sidebhead = (int) memcache_get (self:: $client, $queueName. ' B '. Self::head_key);    $this->sidebtail = (int) memcache_get (self:: $client, $queueName. ' B '. Self::tail_key); }/* Gets the current rotating queue face * @return string queue face name */Public Function getcurrentside () {$currentSide = Me        Mcache_get (self:: $client, $this->queuename. Self::side_key);            if ($currentSide = = ' a ') {$this->currentside = ' a ';              $this->lastside = ' B ';            $this->currenthead = $this->sideahead;            $this->currenttail = $this->sideatail;          $this->lasthead = $this->sidebhead;  $this->lasttail = $this->sidebtail;            }else{$this->currentside = ' B ';            $this->lastside = ' A ';            $this->currenthead = $this->sidebhead;            $this->currenttail = $this->sidebtail;            $this->lasthead = $this->sideahead;                             $this->lasttail = $this->sideatail;    } return $this->currentside;            }/* Queue lock * @return Boolean */Private Function Getlock () {if ($this->access = = = False) {                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 to return false;                Break        }} return $this->access = true;    } return false; }/* * Queue unlocked * @return NULL/Private Function UnLock () {Memcache_delete (self:: $client, $this->queuename. Self::lock_key);    $this->access = false; }/* * Add Data * @param [data] the value to store * @return Boolean */Public Function Add ($data) {$resul        T = false;        if (! $this->getlock ()) {return $result;        } $this->getheadntail ($this->queuename);        $this->getcurrentside ();            if ($this->isfull ()) {$this->unlock ();        return false;  } if ($this->currenttail < Self::maxnum) {$value _key = $this->queuename. $this->currentside. Self::valu_key.            $this->currenttail;                if (Memcache_add (self:: $client, $value _key, $data, False, $this->expire)) {$this->changetail ();            $result = true;            }}else{//the current queue is full, replace the rotating surface $this->unlock ();            $this->changecurrentside (); return $this->adD ($data);        } $this->unlock ();    return $result;        }/* * Take out data * @param [length] int data lengths * @return Array */Public function get ($length =0) {        if (!is_numeric ($length)) return false;        if (empty ($length)) $length = Self::maxnum * 2;//default Read all if (! $this->getlock ()) return false;            if ($this->isempty ()) {$this->unlock ();        return false;        } $keyArray = $this->getkeyarray ($length);        $lastKey = $keyArray [' Lastkey '];        $currentKey = $keyArray [' Currentkey '];        $keys = $keyArray [' Keys '];        $this->changehead ($this->lastside, $lastKey);        $this->changehead ($this->currentside, $currentKey);        $data = @memcache_get (self:: $client, $keys);        foreach ($keys as $v) {//Remove @memcache_delete after removal (self:: $client, $v, 0);        } $this->unlock ();    return $data; }/* * Read data * @param [length] int dataThe length of * @return Array */Public function read ($length =0) {if (!is_numeric ($length)) return false;        if (empty ($length)) $length = Self::maxnum * 2;//reads all $keyArray = $this->getkeyarray ($length) by default;        $data = @memcache_get (self:: $client, $keyArray [' Keys ']);    return $data; }/* Gets the key array for a segment length of the queue * @param [length] int Queue Length * @return array */Private function Getkeyarr        Ay ($length) {$result = array (' Keys ' =>array (), ' Lastkey ' =>array (), ' Currentkey ' =>array ());        $this->getheadntail ($this->queuename);        $this->getcurrentside ();        if (empty ($length)) return $result;        Take the first key $i = $result [' lastkey '] = 0;            for ($i =0; $i < $length; $i + +) {$result [' lastkey '] = $this->lasthead + $i;            if ($result [' Lastkey '] >= $this->lasttail) break; $result [' keys '] = $this->queuename. $this->lastside. Self::valu_key.  $result [' Lastkey '];      }//re-fetch when the previous key $j = $length-$i;        $k = $result [' currentkey '] = 0;            for ($k =0; $k < $j; $k + +) {$result [' currentkey '] = $this->currenthead + $k;            if ($result [' Currentkey '] >= $this->currenttail) break; $result [' keys '] = $this->queuename. $this->currentside. Self::valu_key.        $result [' Currentkey '];    } return $result; }/* Updates the value of the end of the current face queue * @return NULL */Private Function Changetail () {$tail _key = $this->queue Name. $this->currentside.        Self::tail_key;        Memcache_add (self:: $client, $tail _key, 0,false, $this->expire);//if not, insert;        Memcache_increment (self:: $client, $tail _key, 1);//queue end +1 $v = Memcache_get (self:: $client, $tail _key) +1;    Memcache_set (self:: $client, $tail _key, $v, False, $this->expire); }/* Update the value of the queue header * @param [side] string to update the face * @param [headvalue] int queue Header value * @return NUL   L */ Private Function Changehead ($side, $headValue) {if ($headValue < 1) return false; $head _key = $this->queuename. $side.        Self::head_key; $tail _key = $this->queuename. $side.        Self::tail_key;        $sideTail = Memcache_get (self:: $client, $tail _key);        if ($headValue < $sideTail) {Memcache_set (self:: $client, $head _key, $headValue +1,false, $this->expire);        }elseif ($headValue >= $sideTail) {$this->resetside ($side); }/* * Resets the queue polygons, which will set the queue face's first and end values to 0 * @param [side] string to reset the face * @return NULL */Private FUNCT        Ion Resetside ($side) {$head _key = $this->queuename. $side. Self::head_key; $tail _key = $this->queuename. $side.        Self::tail_key;        Memcache_set (self:: $client, $head _key,0,false, $this->expire);    Memcache_set (self:: $client, $tail _key,0,false, $this->expire); }/* Change the current queue face * @return String */Private Function ChangecurrentsiDe () {$currentSide = Memcache_get (self:: $client, $this->queuename. Self::side_key); if ($currentSide = = ' A ') {Memcache_set (self:: $client, $this->queuename. Self::side_key, ' B ', false, $this->e            Xpire);        $this->currentside = ' B ';            }else{Memcache_set (self:: $client, $this->queuename. Self::side_key, ' A ', false, $this->expire);        $this->currentside = ' A ';    } return $this->currentside;        }/* * Check whether the current queue is full * @return Boolean */Public function isfull () {$result = false;        if ($this->sideatail = = Self::maxnum && $this->sidebtail = = self::maxnum) {$result = true;    } return $result;        }/* * Check whether the current queue is empty * @return Boolean/Public Function IsEmpty () {$result = true;        if ($this->sideatail > 0 | | $this->sidebtail > 0) {$result = false;    } return $result; }/* * receivedTake the length of the current queue * This length is theoretical length, some elements are lost due to expiration, the true length is less than or equal to the length * @return int */Public Function Getqueuelength () {$        This->getheadntail ($this->queuename);        $this->getcurrentside ();        $sideALength = $this->sideatail-$this->sideahead;        $sideBLength = $this->sidebtail-$this->sidebhead;        $result = $sideALength + $sideBLength;    return $result;        }/* Clears current queue data, retains only Head_key, Tail_key, side_key three keys * @return Boolean/Public Function clear () {        if (! $this->getlock ()) return false; for ($i =0; $i
 
  
   queuename. ' A '. Self::valu_key. $i, 0);        @memcache_delete (self:: $client, $this->queuename. ' B '. Self::valu_key. $i, 0);        } $this->unlock ();        $this->resetside (' A ');        $this->resetside (' B ');    return true; }/* Clears all memcache cache data * @return NULL */Public Function Memflush () {Memcache_flush (self:: $clie    NT); }}

  
 


http://www.bkjia.com/PHPjc/994954.html www.bkjia.com true http://www.bkjia.com/PHPjc/994954.html techarticle PHP itself implements Memcached Queue class Add (1ASDF); * $obj-getqueuelength (); * $obj-read (one); * $obj-get (8); */class memcachequeue{ public static $client; Memcache Client Connection Pu ...

  • Related Article

    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.