목차
memcacheQueue.class.php" >memcacheQueue.class.php
백엔드 개발 PHP 튜토리얼 php自各儿实现memcached的队列类

php自各儿实现memcached的队列类

Jun 13, 2016 pm 12:19 PM
gt memcache return this

php自己实现memcached的队列类

PHP的memcache队列类
version 0.2
1.修改了changeHead方法,当get(1)只取一条数据时$head_key的值没改变的问题
2.修改了clear方法,当队列较小时按最大队列长度删除的问题

测试结果
队列类添加20000条数据,用时10.390461921692秒
队列类读取20000条数据,用时0.087434053421021秒
队列类取出20000条数据,用时0.91940212249756秒
队列类清空20000条数据,用时0.00077390670776367秒
------------------
PHP扩展添加20000条数据,用时0.9195499420166秒
PHP扩展读取20000条数据,用时0.050693988800049秒
PHP扩展取出20000条数据,用时0.88281202316284秒
PHP扩展删除20000条数据,用时0.81996202468872秒
------------------
队列写入的性能是个问题,待改善
[email protected]

memcacheQueue.class.php

<?php /* * memcache队列类 * 支持多进程并发写入、读取 * 边写边读,AB面轮值替换 * @author lkk/blog.lianq.net * @version 0.2 * @create on 9:25 2012-9-28 * * @edited on 14:03 2013-4-28 * 修改说明: *      1.修改了changeHead方法,当get(1)只取一条数据时$head_key的值没改变的问题 *      2.修改了clear方法,当队列较小时按最大队列长度删除的问题 * * 使用方法: *      $obj = new memcacheQueue(&#39;duilie&#39;); *      $obj->add('1asdf'); *      $obj->getQueueLength(); *      $obj->read(11); *      $obj->get(8); */ class memcacheQueue{    public static   $client;            //memcache客户端连接    public          $access;            //队列是否可更新       private         $currentSide;       //当前轮值的队列面:A/B    private         $lastSide;          //上一轮值的队列面:A/B    private         $sideAHead;         //A面队首值    private         $sideATail;         //A面队尾值    private         $sideBHead;         //B面队首值    private         $sideBTail;         //B面队尾值    private         $currentHead;       //当前队首值    private         $currentTail;       //当前队尾值    private         $lastHead;          //上轮队首值    private         $lastTail;          //上轮队尾值     private         $expire;            //过期时间,秒,1~2592000,即30天内    private         $sleepTime;         //等待解锁时间,微秒    private         $queueName;         //队列名称,唯一值    private         $retryNum;          //重试次数,= 10 * 理论并发数         const   MAXNUM      = 10000;                //(单面)最大队列数,建议上限10K    const   HEAD_KEY    = '_lkkQueueHead_';     //队列首kye    const   TAIL_KEY    = '_lkkQueueTail_';     //队列尾key    const   VALU_KEY    = '_lkkQueueValu_';     //队列值key    const   LOCK_KEY    = '_lkkQueueLock_';     //队列锁key    const   SIDE_KEY    = '_lkkQueueSide_';     //轮值面key         /*     * 构造函数     * @param   [queueName] string  队列名称     * @param   [expire]    string  过期时间     * @param   [config]    array   memcache服务器参数         * @return  NULL     */    public function __construct($queueName ='',$expire='',$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);//当客户断开连接,允许继续执行        set_time_limit(0);//取消脚本执行延时上限                 $this->access = false;        $this->sleepTime = 1000;        $expire = (empty($expire)) ? 3600 : (int)$expire+1;        $this->expire = $expire;        $this->queueName = $queueName;        $this->retryNum = 20000;                 $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->sideBTail) || empty($this->sideBTail)) $this->sideBTail = 0;    }         /*     * 获取队列首尾值     * @param   [queueName] string  队列名称     * @return  NULL     */    private function getHeadNTail($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);    }         /*     * 获取当前轮值的队列面     * @return  string  队列面名称     */    public function getCurrentSide(){        $currentSide = memcache_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;    }         /*     * 队列加锁     * @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){//尝试等待N次                    return false;                    break;                }            }            return $this->access = true;        }        return false;    }         /*     * 队列解锁     * @return NULL     */    private function unLock(){        memcache_delete(self::$client, $this->queueName .self::LOCK_KEY);        $this->access = false;    }         /*     * 添加数据     * @param   [data]  要存储的值     * @return  boolean     */    public function add($data=''){        $result = false;        if(empty($data)) return $result;        if(!$this->getLock()){            return $result;        }         $this->getHeadNTail($this->queueName);        $this->getCurrentSide();                 if($this->isFull()){            $this->unLock();            return false;        }                 if($this->currentTail queueName .$this->currentSide . self::VALU_KEY . $this->currentTail;            if(memcache_set(self::$client, $value_key, $data, false, $this->expire)){                $this->changeTail();                $result = true;            }        }else{//当前队列已满,更换轮值面            $this->unLock();            $this->changeCurrentSide();            return $this->add($data);        }         $this->unLock();        return $result;    }         /*     * 取出数据     * @param   [length]    int 数据的长度     * @return  array     */    public function get($length=0){        if(!is_numeric($length)) return false;        if(empty($length)) $length = self::MAXNUM * 2;//默认读取所有        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);        if(empty($data)) $data = array();        foreach($keys as $v){//取出之后删除            @memcache_delete(self::$client, $v, 0);        }        $this->unLock();         return $data;    }         /*     * 读取数据     * @param   [length]    int 数据的长度     * @return  array     */    public function read($length=0){        if(!is_numeric($length)) return false;        if(empty($length)) $length = self::MAXNUM * 2;//默认读取所有        $keyArray   = $this->getKeyArray($length);        $data   = @memcache_get(self::$client, $keyArray['keys']);        if(empty($data)) $data = array();        return $data;    }         /*     * 获取队列某段长度的key数组     * @param   [length]    int 队列长度     * @return  array     */    private function getKeyArray($length){        $result = array('keys'=>array(),'lastKey'=>null,'currentKey'=>null);        $this->getHeadNTail($this->queueName);        $this->getCurrentSide();        if(empty($length)) return $result;                 //先取上一面的key        $i = $result['lastKey'] = 0;        for($i=0;$ilastHead + $i;            if($result['lastKey'] >= $this->lastTail) break;            $result['keys'][] = $this->queueName .$this->lastSide . self::VALU_KEY . $result['lastKey'];        }                 //再取当前面的key        $j = $length - $i;        $k = $result['currentKey'] = 0;        for($k=0;$kcurrentHead + $k;            if($result['currentKey'] >= $this->currentTail) break;            $result['keys'][] = $this->queueName .$this->currentSide . self::VALU_KEY . $result['currentKey'];        }         return $result;    }         /*     * 更新当前轮值面队列尾的值     * @return  NULL     */    private function changeTail(){        $tail_key = $this->queueName .$this->currentSide . self::TAIL_KEY;        memcache_add(self::$client, $tail_key, 0,false, $this->expire);//如果没有,则插入;有则false;        $v = memcache_get(self::$client, $tail_key) +1;        memcache_set(self::$client, $tail_key,$v,false,$this->expire);    }         /*     * 更新队列首的值     * @param   [side]      string  要更新的面     * @param   [headValue] int     队列首的值     * @return  NULL     */    private function changeHead($side,$headValue){        $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 expire);        }elseif($headValue >= $sideTail){            $this->resetSide($side);        }    }         /*     * 重置队列面,即将该队列面的队首、队尾值置为0     * @param   [side]  string  要重置的面     * @return  NULL     */    private function 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);    }              /*     * 改变当前轮值队列面     * @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->expire);            $this->currentSide = 'B';        }else{            memcache_set(self::$client, $this->queueName . self::SIDE_KEY,'A',false,$this->expire);            $this->currentSide = 'A';        }        return $this->currentSide;    }         /*     * 检查当前队列是否已满     * @return  boolean     */    public function isFull(){        $result = false;        if($this->sideATail == self::MAXNUM && $this->sideBTail == self::MAXNUM){            $result = true;        }        return $result;    }         /*     * 检查当前队列是否为空     * @return  boolean     */    public function isEmpty(){        $result = true;        if($this->sideATail > 0 || $this->sideBTail > 0){            $result = false;        }        return $result;    }         /*     * 获取当前队列的长度     * 该长度为理论长度,某些元素由于过期失效而丢失,真实长度小于或等于该长度     * @return  int     */    public function getQueueLength(){        $this->getHeadNTail($this->queueName);         $sideALength = $this->sideATail - $this->sideAHead;        $sideBLength = $this->sideBTail - $this->sideBHead;        $result = $sideALength + $sideBLength;                 return $result;    }          /*     * 清空当前队列数据,仅保留HEAD_KEY、TAIL_KEY、SIDE_KEY三个key     * @return  boolean     */    public function clear(){        if(!$this->getLock()) return false;        $this->getHeadNTail($this->queueName);        $AHead = $this->sideAHead;$AHead--;        $ATail = $this->sideATail;$ATail++;        $BHead = $this->sideBHead;$BHead--;              $BTail = $this->sideBTail;$BTail++;                 //删除A面        for($i=$AHead;$iqueueName.'A'. self::VALU_KEY .$i, 0);        }                 //删除B面        for($j=$BHead;$jqueueName.'A'. self::VALU_KEY .$j, 0);        }         $this->unLock();        $this->resetSide('A');        $this->resetSide('B');        return true;    }         /*     * 清除所有memcache缓存数据     * @return  NULL     */    public function memFlush(){        memcache_flush(self::$client);    }   }
로그인 후 복사

test.php

<?php //memcacheQueue队列类测试header("Content-type: text/html; charset=utf-8;private, must-revalidate");require_once(&#39;memcacheQueue.class.php&#39;);//获取时间,精度微秒function microtimeFloat(){    list($usec, $sec) = explode(" ", microtime());    return ((float)$usec + (float)$sec);}  $queObj = new memcacheQueue(&#39;duilie&#39;);$client = memcache_pconnect(&#39;127.0.0.1&#39;,11211);$length = 20000;  /*------------------------------------------ * 队列类测试 *------------------------------------------ */ //写数据$time_add_start = microtimeFloat();for($i=1;$i<=$length;$i++){    $queObj->add($i);}$time_add_end = microtimeFloat();$count = $queObj->getQueueLength();$time_use = $time_add_end - $time_add_start;echo "队列类添加{$count}条数据,用时{$time_use}秒<br>"; //读数据$time_read_start = microtimeFloat();$tmpArr = $queObj->read();$time_read_end = microtimeFloat();$count = $queObj->getQueueLength();$time_use = $time_read_end - $time_read_start;echo "队列类读取{$count}条数据,用时{$time_use}秒<br>"; //取出数据$time_get_start = microtimeFloat();$tmpArr = $queObj->get();$time_get_end = microtimeFloat();$count = count($tmpArr);$time_use = $time_get_end - $time_get_start;echo "队列类取出{$count}条数据,用时{$time_use}秒<br>"; //清空队列$time_clear_start = microtimeFloat();$queObj->clear();$time_clear_end = microtimeFloat();$time_use = $time_clear_end - $time_clear_start;echo "队列类清空{$count}条数据,用时{$time_use}秒<br>"; echo "<hr><br>"; /*------------------------------------------ * PHP memcache扩展测试 *------------------------------------------ */ //写数据$time_add_start = microtimeFloat();for($i=1;$i"; //读数据$time_read_start = microtimeFloat();$keyArr = array();for($i=1;$i"; //取出数据//读数据$time_get_start = microtimeFloat();$keyArr = array();for($i=1;$i";$time_use2 = $time_get_end2 - $time_get_end1;echo "PHP扩展删除{$coutn}条数据,用时{$time_use2}秒<br>";
로그인 후 복사


本文来自:http://www.oschina.net/code/snippet_111731_20890

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? 화웨이 GT3 Pro와 GT4의 차이점은 무엇입니까? Dec 29, 2023 pm 02:27 PM

많은 사용자들이 스마트 시계를 선택할 때 Huawei 브랜드를 선택하게 됩니다. 그 중 Huawei GT3pro와 GT4가 가장 인기 있는 선택입니다. 두 제품의 차이점을 궁금해하는 사용자가 많습니다. Huawei GT3pro와 GT4의 차이점은 무엇입니까? 1. 외관 GT4: 46mm와 41mm, 재질은 유리 거울 + 스테인레스 스틸 본체 + 고해상도 섬유 후면 쉘입니다. GT3pro: 46.6mm 및 42.9mm, 재질은 사파이어 유리 + 티타늄 본체/세라믹 본체 + 세라믹 백 쉘입니다. 2. 건강한 GT4: 최신 Huawei Truseen5.5+ 알고리즘을 사용하면 결과가 더 정확해집니다. GT3pro: ECG 심전도, 혈관 및 안전성 추가

C 언어의 return 사용법에 대한 자세한 설명 C 언어의 return 사용법에 대한 자세한 설명 Oct 07, 2023 am 10:58 AM

C 언어에서 return의 사용법은 다음과 같습니다. 1. 반환 값 유형이 void인 함수의 경우 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 2. 반환 값 유형이 void가 아닌 함수의 경우 return 문은 함수 실행을 종료하는 것입니다. 결과는 호출자에게 반환됩니다. 3. 함수 실행을 조기에 종료합니다. 함수 내부에서는 return 문을 사용하여 함수 실행을 조기에 종료할 수 있습니다. 함수가 값을 반환하지 않는 경우.

PHP 개발에 Memcache를 어떻게 사용하나요? PHP 개발에 Memcache를 어떻게 사용하나요? Nov 07, 2023 pm 12:49 PM

웹 개발에서는 웹사이트 성능과 응답 속도를 향상시키기 위해 캐싱 기술을 사용해야 하는 경우가 많습니다. Memcache는 모든 데이터 유형을 캐시할 수 있고 높은 동시성 및 고가용성을 지원하는 널리 사용되는 캐싱 기술입니다. 이 기사에서는 PHP 개발에 Memcache를 사용하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. Memcache 설치 Memcache를 사용하려면 먼저 서버에 Memcache 확장 프로그램을 설치해야 합니다. CentOS 운영 체제에서는 다음 명령을 사용할 수 있습니다.

수정: Windows 11에서 캡처 도구가 작동하지 않음 수정: Windows 11에서 캡처 도구가 작동하지 않음 Aug 24, 2023 am 09:48 AM

Windows 11에서 캡처 도구가 작동하지 않는 이유 문제의 근본 원인을 이해하면 올바른 솔루션을 찾는 데 도움이 될 수 있습니다. 캡처 도구가 제대로 작동하지 않는 주요 이유는 다음과 같습니다. 초점 도우미가 켜져 있습니다. 이렇게 하면 캡처 도구가 열리지 않습니다. 손상된 응용 프로그램: 캡처 도구가 실행 시 충돌하는 경우 응용 프로그램이 손상되었을 수 있습니다. 오래된 그래픽 드라이버: 호환되지 않는 드라이버가 캡처 도구를 방해할 수 있습니다. 다른 응용 프로그램의 간섭: 실행 중인 다른 응용 프로그램이 캡처 도구와 충돌할 수 있습니다. 인증서가 만료되었습니다. 업그레이드 프로세스 중 오류로 인해 이 문제가 발생할 수 있습니다. 이 문제는 대부분의 사용자에게 적합하며 특별한 기술 지식이 필요하지 않습니다. 1. Windows 및 Microsoft Store 앱 업데이트

iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 iPhone에서 App Store 오류에 연결할 수 없는 문제를 해결하는 방법 Jul 29, 2023 am 08:22 AM

1부: 초기 문제 해결 단계 Apple 시스템 상태 확인: 복잡한 솔루션을 살펴보기 전에 기본 사항부터 시작해 보겠습니다. 문제는 귀하의 기기에 있는 것이 아닐 수도 있습니다. Apple 서버가 다운되었을 수도 있습니다. Apple의 시스템 상태 페이지를 방문하여 AppStore가 제대로 작동하는지 확인하세요. 문제가 있는 경우 Apple이 문제를 해결하기를 기다리는 것뿐입니다. 인터넷 연결 확인: "AppStore에 연결할 수 없음" 문제는 때때로 연결 불량으로 인해 발생할 수 있으므로 인터넷 연결이 안정적인지 확인하십시오. Wi-Fi와 모바일 데이터 간을 전환하거나 네트워크 설정을 재설정해 보세요(일반 > 재설정 > 네트워크 설정 재설정 > 설정). iOS 버전을 업데이트하세요.

PHP 개발에서 효율적인 데이터 읽기 및 쓰기 작업을 위해 Memcache를 사용하는 방법은 무엇입니까? PHP 개발에서 효율적인 데이터 읽기 및 쓰기 작업을 위해 Memcache를 사용하는 방법은 무엇입니까? Nov 07, 2023 pm 03:48 PM

PHP 개발에서 Memcache 캐싱 시스템을 사용하면 데이터 읽기 및 쓰기 효율성을 크게 향상시킬 수 있습니다. Memcache는 데이터베이스를 자주 읽고 쓰지 않도록 메모리에 데이터를 캐시할 수 있는 메모리 기반 캐싱 시스템입니다. 이 기사에서는 효율적인 데이터 읽기 및 쓰기 작업을 위해 PHP에서 Memcache를 사용하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. Memcache 설치 및 구성 먼저 서버에 Memcache 확장 프로그램을 설치해야 합니다. 합격할 수 있다

PHP 개발에서 효율적인 데이터 쓰기 및 쿼리를 위해 Memcache를 사용하는 방법은 무엇입니까? PHP 개발에서 효율적인 데이터 쓰기 및 쿼리를 위해 Memcache를 사용하는 방법은 무엇입니까? Nov 07, 2023 pm 01:36 PM

PHP 개발에서 효율적인 데이터 쓰기 및 쿼리를 위해 Memcache를 사용하는 방법은 무엇입니까? 인터넷 애플리케이션의 지속적인 개발로 인해 시스템 성능에 대한 요구 사항이 점점 더 높아지고 있습니다. PHP 개발에서는 시스템 성능과 응답 속도를 향상시키기 위해 다양한 캐싱 기술을 사용하는 경우가 많습니다. 일반적으로 사용되는 캐싱 기술 중 하나는 Memcache입니다. Memcache는 데이터베이스 쿼리 결과, 페이지 조각, 세션 데이터 등을 캐시하는 데 사용할 수 있는 고성능 분산 메모리 객체 캐싱 시스템입니다. 데이터를 메모리에 저장함으로써

JavaScript에서 return 키워드 사용 JavaScript에서 return 키워드 사용 Feb 18, 2024 pm 12:45 PM

JavaScript에서 return을 사용하려면 특정 코드 예제가 필요합니다. JavaScript에서 return 문은 함수에서 반환되는 값을 지정하는 데 사용됩니다. 함수 실행을 종료하는 데 사용할 수 있을 뿐만 아니라 함수가 호출된 위치에 값을 반환할 수도 있습니다. return 문에는 다음과 같은 일반적인 용도가 있습니다. 값 반환 return 문은 함수가 호출된 위치에 값을 반환하는 데 사용할 수 있습니다. 다음은 간단한 예입니다: functionadd(a,b){

See all articles