목차
php自己实现memcached的队列类
백엔드 개발 PHP 튜토리얼 php自己实现memcached的队列类_PHP教程

php自己实现memcached的队列类_PHP教程

Jul 13, 2016 am 09:54 AM
대기줄

php自己实现memcached的队列类

 

 

<!--?php
/*
 * memcache队列类
 * 支持多进程并发写入、读取
 * 边写边读,AB面轮值替换
 * @author guoyu
 * @create on 9:25 2014-9-28
 * @qq技术行业交流群:136112330
 *
 * @example:
 *      $obj = new memcacheQueue(&#39;duilie&#39;);
 *      $obj--->add(&#39;1asdf&#39;);
 *      $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天内;0为永不过期
    private         $sleepTime;         //等待解锁时间,微秒
    private         $queueName;         //队列名称,唯一值
    private         $retryNum;          //重试次数,= 10 * 理论并发数

    const   MAXNUM      = 2000;                 //(单面)最大队列数,建议上限10K
    const   HEAD_KEY    = &#39;_lkkQueueHead_&#39;;     //队列首kye
    const   TAIL_KEY    = &#39;_lkkQueueTail_&#39;;     //队列尾key
    const   VALU_KEY    = &#39;_lkkQueueValu_&#39;;     //队列值key
    const   LOCK_KEY    = &#39;_lkkQueueLock_&#39;;     //队列锁key
    const   SIDE_KEY    = &#39;_lkkQueueSide_&#39;;     //轮值面key

    /*
     * 构造函数
     * @param   [config]    array   memcache服务器参数
     * @param   [queueName] string  队列名称
     * @param   [expire]    string  过期时间
     * @return  NULL
     */
    public function __construct($queueName =&#39;&#39;,$expire=&#39;&#39;,$config =&#39;&#39;){
        if(empty($config)){
            self::$client = memcache_pconnect(&#39;localhost&#39;,11211);
        }elseif(is_array($config)){//array(&#39;host&#39;=>&#39;127.0.0.1&#39;,&#39;port&#39;=>&#39;11211&#39;)
            self::$client = memcache_pconnect($config[&#39;host&#39;],$config[&#39;port&#39;]);
        }elseif(is_string($config)){//"127.0.0.1:11211"
            $tmp = explode(&#39;:&#39;,$config);
            $conf[&#39;host&#39;] = isset($tmp[0]) ? $tmp[0] : &#39;127.0.0.1&#39;;
            $conf[&#39;port&#39;] = isset($tmp[1]) ? $tmp[1] : &#39;11211&#39;;
            self::$client = memcache_pconnect($conf[&#39;host&#39;],$conf[&#39;port&#39;]);     
        }
        if(!self::$client) return false;

        ignore_user_abort(TRUE);//当客户断开连接,允许继续执行
        set_time_limit(0);//取消脚本执行延时上限

        $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, &#39;A&#39;,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;
    }

    /*
     * 获取队列首尾值
     * @param   [queueName] string  队列名称
     * @return  NULL
     */
    private function getHeadNTail($queueName){
        $this->sideAHead = (int)memcache_get(self::$client, $queueName.&#39;A&#39;. self::HEAD_KEY);
        $this->sideATail = (int)memcache_get(self::$client, $queueName.&#39;A&#39;. self::TAIL_KEY);
        $this->sideBHead = (int)memcache_get(self::$client, $queueName.&#39;B&#39;. self::HEAD_KEY);
        $this->sideBTail = (int)memcache_get(self::$client, $queueName.&#39;B&#39;. self::TAIL_KEY);
    }

    /*
     * 获取当前轮值的队列面
     * @return  string  队列面名称
     */
    public function getCurrentSide(){
        $currentSide = memcache_get(self::$client, $this->queueName . self::SIDE_KEY);
        if($currentSide == &#39;A&#39;){
            $this->currentSide = &#39;A&#39;;
            $this->lastSide = &#39;B&#39;;  

            $this->currentHead  = $this->sideAHead;
            $this->currentTail  = $this->sideATail;
            $this->lastHead     = $this->sideBHead;
            $this->lastTail     = $this->sideBTail;         
        }else{
            $this->currentSide = &#39;B&#39;;
            $this->lastSide = &#39;A&#39;;

            $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(!$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{//当前队列已满,更换轮值面
            $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[&#39;lastKey&#39;];
        $currentKey = $keyArray[&#39;currentKey&#39;];
        $keys       = $keyArray[&#39;keys&#39;];
        $this->changeHead($this->lastSide,$lastKey);
        $this->changeHead($this->currentSide,$currentKey);

        $data   = @memcache_get(self::$client, $keys);
        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[&#39;keys&#39;]);
        return $data;
    }

    /*
     * 获取队列某段长度的key数组
     * @param   [length]    int 队列长度
     * @return  array
     */
    private function getKeyArray($length){
        $result = array(&#39;keys&#39;=>array(),&#39;lastKey&#39;=>array(),&#39;currentKey&#39;=>array());
        $this->getHeadNTail($this->queueName);
        $this->getCurrentSide();
        if(empty($length)) return $result;

        //先取上一面的key
        $i = $result[&#39;lastKey&#39;] = 0;
        for($i=0;$i<$length;$i++){
            $result[&#39;lastKey&#39;] = $this->lastHead + $i;
            if($result[&#39;lastKey&#39;] >= $this->lastTail) break;
            $result[&#39;keys&#39;][] = $this->queueName .$this->lastSide . self::VALU_KEY . $result[&#39;lastKey&#39;];
        }

        //再取当前面的key
        $j = $length - $i;
        $k = $result[&#39;currentKey&#39;] = 0;
        for($k=0;$k<$j;$k++){
            $result[&#39;currentKey&#39;] = $this->currentHead + $k;
            if($result[&#39;currentKey&#39;] >= $this->currentTail) break;
            $result[&#39;keys&#39;][] = $this->queueName .$this->currentSide . self::VALU_KEY . $result[&#39;currentKey&#39;];
        }

        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;
        //memcache_increment(self::$client, $tail_key, 1);//队列尾+1
        $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){
        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);
        }
    }

    /*
     * 重置队列面,即将该队列面的队首、队尾值置为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 == &#39;A&#39;){
            memcache_set(self::$client, $this->queueName . self::SIDE_KEY,&#39;B&#39;,false,$this->expire);
            $this->currentSide = &#39;B&#39;;
        }else{
            memcache_set(self::$client, $this->queueName . self::SIDE_KEY,&#39;A&#39;,false,$this->expire);
            $this->currentSide = &#39;A&#39;;
        }
        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);
        $this->getCurrentSide();

        $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;
        for($i=0;$i<self::maxnum;$i++){ this-="">queueName.&#39;A&#39;. self::VALU_KEY .$i, 0);
            @memcache_delete(self::$client, $this->queueName.&#39;B&#39;. self::VALU_KEY .$i, 0);
        }
        $this->unLock();
        $this->resetSide(&#39;A&#39;);
        $this->resetSide(&#39;B&#39;);
        return true;
    }

    /*
     * 清除所有memcache缓存数据
     * @return  NULL
     */
    public function memFlush(){
        memcache_flush(self::$client);
    }

}
</self::maxnum;$i++){>
로그인 후 복사


 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/994954.htmlTechArticlephp自己实现memcached的队列类 add(1asdf); * $obj-getQueueLength(); * $obj-read(11); * $obj-get(8); */class memcacheQueue{ public static $client; //memcache客户端连接 pu...
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Python의 Deque: 효율적인 큐 및 스택 구현 Python의 Deque: 효율적인 큐 및 스택 구현 Apr 12, 2023 pm 09:46 PM

Python의 deque는 컴퓨팅에서 가장 일반적인 목록 기반 데이터 유형인 우아하고 효율적인 Python 대기열 및 스택을 구현하는 데 유용한 저수준의 고도로 최적화된 deque입니다. 이 기사에서 Yun Duo는 다음 사항을 함께 학습합니다: deque를 사용하여 요소를 효과적으로 팝업하고 추가합니다. deque를 사용하여 효율적인 대기열을 만듭니다. Python 목록 및 팝업 요소의 끝 작업은 일반적으로 매우 효율적입니다. 시간 복잡도를 Big O로 표현하면 O(1)이라고 말할 수 있습니다. 그리고 Python이 새 요소를 허용하기 위해 기본 목록을 늘리기 위해 메모리를 재할당해야 할 때,

ThinkPHP6 대기열을 관리하기 위해 Supervisor를 사용하는 방법은 무엇입니까? ThinkPHP6 대기열을 관리하기 위해 Supervisor를 사용하는 방법은 무엇입니까? Jun 12, 2023 am 08:51 AM

웹 애플리케이션이 계속해서 개발됨에 따라 애플리케이션의 안정성과 가용성을 유지하기 위해 수많은 작업을 처리해야 합니다. 대기열 시스템을 사용하는 것이 하나의 솔루션입니다. ThinkPHP6은 작업을 관리하기 위한 내장형 대기열 시스템을 제공합니다. 그러나 많은 수의 작업을 처리하려면 더 나은 대기열 관리가 필요하며 이는 Supervisor를 사용하여 달성할 수 있습니다. 이 문서에서는 Supervisor를 사용하여 ThinkPHP6 대기열을 관리하는 방법을 소개합니다. 그 전에 몇 가지 기본 개념을 이해해야 합니다. 대기열 시스템 대기열 시스템은

PHP 및 MySQL의 메시지 지연 및 메시지 재시도에 큐 기술 적용 PHP 및 MySQL의 메시지 지연 및 메시지 재시도에 큐 기술 적용 Oct 15, 2023 pm 02:26 PM

PHP 및 MySQL의 메시지 지연 및 메시지 재시도에 대한 큐 기술 적용 요약: 웹 애플리케이션의 지속적인 개발로 인해 높은 동시 처리 및 시스템 안정성에 대한 요구가 점점 더 높아지고 있습니다. 이에 대한 해결책으로 큐 기술은 메시지 지연 및 메시지 재시도 기능을 구현하기 위해 PHP 및 MySQL에서 널리 사용됩니다. 이 기사에서는 큐의 기본 원리, 큐를 사용하여 메시지 지연을 구현하는 방법, 큐를 사용하여 메시지 재시도를 구현하는 방법을 포함하여 PHP 및 MySQL의 큐 기술 적용을 소개하고 다음을 제공합니다.

Java Queue 큐 성능 분석 및 최적화 전략 Java Queue 큐 성능 분석 및 최적화 전략 Jan 09, 2024 pm 05:02 PM

JavaQueue의 성능 분석 및 최적화 전략 큐 요약: 큐(Queue)는 Java에서 일반적으로 사용되는 데이터 구조 중 하나이며 다양한 시나리오에서 널리 사용됩니다. 이 기사에서는 성능 분석 및 최적화 전략이라는 두 가지 측면에서 JavaQueue 대기열의 성능 문제를 논의하고 특정 코드 예제를 제공합니다. 소개 큐는 생산자-소비자 모드, 스레드 풀 작업 큐 및 기타 시나리오를 구현하는 데 사용할 수 있는 FIFO(선입선출) 데이터 구조입니다. Java는 Arr과 같은 다양한 대기열 구현을 제공합니다.

Java에서 대기열의 add() 메소드와 Offer() 메소드의 차이점은 무엇입니까? Java에서 대기열의 add() 메소드와 Offer() 메소드의 차이점은 무엇입니까? Aug 27, 2023 pm 02:25 PM

Java의 큐는 여러 기능을 갖춘 선형 데이터 구조입니다. 큐에는 두 개의 엔드포인트가 있으며 해당 요소를 삽입하고 삭제하는 데 FIFO(선입선출) 원칙을 따릅니다. 이 튜토리얼에서는 add()와 Offer()라는 Java 대기열의 두 가지 중요한 기능에 대해 알아봅니다. 대기열이란 무엇입니까? Java의 대기열은 util 및 컬렉션 패키지를 확장하는 인터페이스입니다. 요소는 백엔드에 삽입되고 프런트엔드에서 제거됩니다. Java의 대기열은 연결 목록, DeQueue 및 우선 순위 대기열과 같은 클래스를 사용하여 구현할 수 있습니다. 우선순위 큐는 일반 큐의 확장된 형태로, 각 요소에는 우선순위가 있습니다. 큐의 add() 메소드는 큐에 요소를 삽입하는 데 사용됩니다. 요소를 정의합니다(

PHP 및 MySQL의 대기열 작업 모니터링 및 작업 스케줄링 구현 계획 PHP 및 MySQL의 대기열 작업 모니터링 및 작업 스케줄링 구현 계획 Oct 15, 2023 am 09:15 AM

PHP 및 MySQL에서 대기열 작업 모니터링 및 작업 예약 구현 소개 현대 웹 애플리케이션 개발에서 작업 대기열은 매우 중요한 기술입니다. 큐를 통해 백그라운드에서 실행해야 하는 일부 작업을 대기열에 넣을 수 있고, 작업 스케줄링을 통해 작업의 실행 시간과 순서를 제어할 수 있습니다. 이 기사에서는 PHP 및 MySQL에서 작업 모니터링 및 예약을 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 큐의 작동 원리 큐는 다음 작업에 사용할 수 있는 FIFO(선입선출) 데이터 구조입니다.

PHP 메일 큐 시스템의 원리와 구현은 무엇입니까? PHP 메일 큐 시스템의 원리와 구현은 무엇입니까? Sep 13, 2023 am 11:39 AM

PHP 메일 큐 시스템의 원리와 구현은 무엇입니까? 인터넷의 발달과 함께 이메일은 사람들의 일상생활과 업무에서 없어서는 안 될 의사소통 수단 중 하나가 되었습니다. 그러나 사업이 성장하고 사용자 수가 증가함에 따라 이메일을 직접 보내는 경우 서버 성능 저하, 이메일 전달 실패 등의 문제가 발생할 수 있습니다. 이 문제를 해결하기 위해 메일 대기열 시스템을 사용하여 직렬 대기열을 통해 이메일을 보내고 관리할 수 있습니다. 메일 대기열 시스템의 구현 원리는 다음과 같습니다. 메일이 대기열에 들어갈 때, 메일을 보내야 할 때 더 이상 직접적으로 메일을 보내지 않습니다.

Yii 프레임워크의 대기열: 비동기 작업을 효율적으로 처리하기 Yii 프레임워크의 대기열: 비동기 작업을 효율적으로 처리하기 Jun 21, 2023 am 10:13 AM

인터넷의 급속한 발전으로 인해 많은 수의 동시 요청과 작업을 처리하는 데 애플리케이션이 점점 더 중요해지고 있습니다. 이러한 경우 비동기 작업을 처리하는 것이 필수적입니다. 이를 통해 애플리케이션이 더 효율적이고 사용자 요청에 더 잘 응답할 수 있기 때문입니다. Yii 프레임워크는 비동기 작업을 보다 쉽고 효율적으로 처리할 수 있는 편리한 대기열 구성 요소를 제공합니다. 이 기사에서는 Yii 프레임워크에서 대기열의 사용과 이점을 살펴보겠습니다. 큐란 무엇입니까? 큐는 FIFO(선입선출) 순서로 데이터를 처리하는 데 사용되는 데이터 구조입니다. 팀

See all articles