백엔드 개발 PHP 튜토리얼 强大的PHP缓存种(eaccelerator、apc、xcache、memcache模块缓存)

强大的PHP缓存种(eaccelerator、apc、xcache、memcache模块缓存)

Jun 13, 2016 pm 01:09 PM
cache eaccelerator function gt this

强大的PHP缓存类(eaccelerator、apc、xcache、memcache模块缓存)

<?php /*
 * Name:    wrapperCache
 * URL:     http://www.admpub.com/
 * Version: v0.1
 * Date:    29/10/2010
 * Author:  Chema Garrido
 * License: GPL v3
 * Notes:   wrapper cache for fileCache, memcache, APC, Xcache and eaccelerator
 */
 
class wrapperCache {
    private $cache_params;//extra params for external caches like path or connection option memcached
    public $cache_expire;//seconds that the cache expires
    private $cache_type;//type of cache to use
    private $cache_external; //external instance of cache, can be fileCache or memcache
    private static $instance;//Instance of this class
         
    // Always returns only one instance
    public static function GetInstance($type='auto',$exp_time=3600,$params='cache/'){
        if (!isset(self::$instance)){//doesn't exists the isntance
             self::$instance = new self($type,$exp_time,$params);//goes to the constructor
        }
        return self::$instance;
    }
     
    //cache constructor, optional expiring time and cache path
    private function __construct($type,$exp_time,$params){
        $this->cache_expire=$exp_time;
        $this->cache_params=$params;
        $this->setCacheType($type);
    }
     
    public function __destruct() {
        unset($this->cache_external);
    }
     
    // Prevent users to clone the instance
    public function __clone(){
        $this->cacheError('Clone is not allowed.');
    }
     
    //deletes cache from folder
    public function clearCache(){
        switch($this->cache_type){
            case 'eaccelerator':
                @eaccelerator_clean();
                @eaccelerator_clear();
            break;
 
            case 'apc':
                apc_clear_cache('user');
            break;
 
            case 'xcache':
                xcache_clear_cache(XC_TYPE_VAR, 0);
            break;
 
            case 'memcache':
                @$this->cache_external->flush();
            break;
             
            case 'filecache':
                $this->cache_external->deleteCache();
            break;
        }  
    }
     
    //writes or reads the cache
    public function cache($key, $value='',$ttl=''){
        if ($value!=''){//wants to write
            if ($ttl=='') $ttl=$this->cache_expire;
            $this->put($key, $value,$ttl);
        }
        else return $this->get($key);//reading value
    }
     
    //creates new cache files with the given data, $key== name of the cache, data the info/values to store
    private function put($key,$data,$ttl='' ){
        if ($ttl=='') $ttl=$this->cache_expire;
         
        switch($this->cache_type){
            case 'eaccelerator':
                eaccelerator_put($key, serialize($data), $ttl);
            break;
 
            case 'apc':
                apc_store($key, $data, $ttl);
            break;
 
            case 'xcache':
                xcache_set($key, serialize($data), $ttl);
            break;
 
            case 'memcache':
                $data=serialize($data);
                if (!$this->cache_external->replace($key, $data, false, $ttl))
                $this->cache_external->set($key, $data, false, $ttl);
            break;
             
            case 'filecache':
                $this->cache_external->cache($key,$data);
            break;
        }  
    }
     
    //returns cache for the given key
    private function get($key){
        switch($this->cache_type){
            case 'eaccelerator':
                $data =  @unserialize(eaccelerator_get($key));
            break;
 
            case 'apc':
                $data =  apc_fetch($key);
            break;
 
            case 'xcache':
                $data =  @unserialize(xcache_get($key));
            break;
 
            case 'memcache':
                $data = @unserialize($this->cache_external->get($key));
            break;
             
            case 'filecache':
                $data = $this->cache_external->cache($key);
            break;
        }  
        /*echo '<br>--returnning data for key:'.$key;
        var_dump($data);*/
        return $data;
    }
     
    //delete key from cache
    public function delete($key){
        switch($this->cache_type){
            case 'eaccelerator':
                eaccelerator_rm($key);
            break;
 
            case 'apc':
                apc_delete($key);
            break;
 
            case 'xcache':
                xcache_unset($key);
            break;
 
            case 'memcache':
                $this->cache_external->delete($key);
            break;
             
            case 'filecache':
                $this->cache_external->delete($key);
            break;
        }  
     
    }
    // Overloading for the Application variables and automatically cached
        public function __set($name, $value) {
            $this->put($name, $value, $this->cache_expire);
        }
     
        public function __get($name) {
            return $this->get($name);
        }
     
        public function __isset($key) {//echo "Is '$name' set?\n"
            if ($this->get($key) !== false)  return true;
            else return false;
        }
     
        public function __unset($name) {//echo "Unsetting '$name'\n";
            $this->delete($name);
        }
    //end overloads
     
    public function getCacheType(){
        return $this->$this->cache_type;
    }  
     
    //sets the cache if its installed if not triggers error
    public function setCacheType($type){
        $this->cache_type=strtolower($type);
         
        switch($this->cache_type){
            case 'eaccelerator':
                if (function_exists('eaccelerator_get')) $this->cache_type = 'eaccelerator';
                else $this->cacheError('eaccelerator not found');   
            break;
 
            case 'apc':
                if (function_exists('apc_fetch')) $this->cache_type = 'apc' ;
                else $this->cacheError('APC not found'); 
            break;
 
            case 'xcache':
                if (function_exists('xcache_get')) $this->cache_type = 'xcache' ;
                else $this->cacheError('Xcache not found');
            break;
 
            case 'memcache':
                if (class_exists('Memcache')) $this->init_memcache();
                else $this->cacheError('memcache not found');
            break;
             
            case 'filecache':
                if (class_exists('fileCache'))$this->init_filecache();
                else $this->cacheError('fileCache not found');
            break;
             
            case 'auto'://try to auto select a cache system
                if (function_exists('eaccelerator_get'))    $this->cache_type = 'eaccelerator';                                      
                elseif (function_exists('apc_fetch'))       $this->cache_type = 'apc' ;                                    
                elseif (function_exists('xcache_get'))      $this->cache_type = 'xcache' ;                                       
                elseif (class_exists('Memcache'))           $this->init_memcache();
                elseif (class_exists('fileCache'))          $this->init_filecache();
                else $this->cacheError('not any compatible cache was found');
            break;
             
            default://not any cache selected or wrong one selected
                if (isset($type)) $msg='Unrecognized cache type selected <b>'.$type.'</b>';
                else $msg='Not any cache type selected';
                $this->cacheError($msg);    
            break;
        }
    }  
         
    private function init_memcache(){//get instance of the memcache class
        if (is_array($this->cache_params)){
            $this->cache_type = 'memcache';
            $this->cache_external = new Memcache;
            foreach ($this->cache_params as $server) {
                $server['port'] = isset($server['port']) ? (int) $server['port'] : ini_get('memcache.default_port');
                $server['persistent'] = isset($server['persistent']) ? (bool) $server['persistent'] : true;
                $this->cache_external->addServer($server['host'], $server['port'], $server['persistent']);
            }
        }
        else $this->cacheError('memcache needs an array, example:
                    wrapperCache::GetInstance(\'memcache\',30,array(array(\'host\'=>\'localhost\')));');
    }
     
    private function init_filecache(){//get instance of the filecache class
        $this->cache_type = 'filecache';
        $this->cache_external = fileCache::GetInstance($this->cache_expire,$this->cache_params);
    }
     
    public function getAvailableCache($return_format='html'){//returns the available cache
        $avCaches   = array();
        $avCaches[] = array('eaccelerator',function_exists('eaccelerator_get'));                                      
        $avCaches[] = array('apc',function_exists('apc_fetch')) ;                                    
        $avCaches[] = array('xcache',function_exists('xcache_get'));                                       
        $avCaches[] = array('memcache',class_exists('Memcache'));
        $avCaches[] = array('fileCache',class_exists('fileCache'));
         
        if ($return_format=='html'){
            $ret='
로그인 후 복사
    '; foreach ($avCaches as $c){ $ret.='
  • '.$c[0].' - '; if ($c[1]) $ret.='Found/Compatible'; else $ret.='Not Found/Incompatible'; $ret.=''; } return $ret.'
'; } else return $avCaches; } private function cacheError($msg){//triggers error trigger_error('
wrapperCache error: '.$msg. '
If you want you can try with \'auto\' for auto select a compatible cache.
Or choose a supported cache from list:'.$this->getAvailableCache(), E_USER_ERROR); } } ?>

?基于文件的

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 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. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++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 심전도, 혈관 및 안전성 추가

입사하고 나서 Cache가 뭔지 이해하게 됐어요 입사하고 나서 Cache가 뭔지 이해하게 됐어요 Jul 31, 2023 pm 04:03 PM

실제로는 이렇습니다. 당시 리더가 perf 하드웨어 성능 모니터링 작업을 지시했습니다. perf를 사용하는 동안 perf list 명령을 입력했는데 다음 정보가 표시되었습니다. 내 작업은 이러한 캐시 이벤트를 활성화하는 것입니다. 하지만 요점은 이러한 누락과 로드가 무엇을 의미하는지 전혀 모른다는 것입니다.

기능은 무슨 뜻인가요? 기능은 무슨 뜻인가요? Aug 04, 2023 am 10:33 AM

함수는 특정 기능을 포함하는 재사용 가능한 코드 블록으로, 입력 매개변수를 받아들이고 특정 작업을 수행하며 결과를 반환하는 것이 목적입니다. 코드 재사용성과 유지 관리성을 향상시키는 코드입니다.

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

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

캐시를 사용하면 컴퓨터 속도가 빨라지는 이유는 무엇입니까? 캐시를 사용하면 컴퓨터 속도가 빨라지는 이유는 무엇입니까? Dec 09, 2020 am 11:28 AM

캐시를 사용하면 CPU의 대기 시간이 단축되므로 컴퓨터 속도가 향상될 수 있습니다. 캐시는 CPU와 메인 메모리 DRAM 사이에 위치한 작지만 고속의 메모리입니다. 캐시의 기능은 CPU 데이터 입출력 속도를 높이는 것입니다. 캐시는 용량은 작지만 속도가 빠르며, 메모리 속도는 낮지만 용량이 큽니다. 시스템 성능은 향상됩니다. 크게 개선되었습니다.

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

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

캐시란 무엇입니까? 캐시란 무엇입니까? Nov 25, 2022 am 11:48 AM

캐시(Cache)는 캐시 메모리(Cache Memory)라고 하며 중앙처리장치와 메인 메모리 사이에 있는 고속 소용량 메모리로 일반적으로 고속 SRAM으로 구성된다. CPU와 메모리 사이의 속도 차이가 시스템 성능에 미치는 영향을 줄이거 나 제거합니다. 캐시 용량은 작지만 빠르며, 메모리 속도는 낮지만 용량이 큽니다. 스케줄링 알고리즘을 최적화하면 시스템 성능이 크게 향상됩니다.

nginx 역방향 프록시 캐싱 튜토리얼. nginx 역방향 프록시 캐싱 튜토리얼. Feb 18, 2024 pm 04:48 PM

다음은 nginx 역방향 프록시 캐싱에 대한 튜토리얼입니다. nginx 설치: sudoaptupdatesudoaptinstallnginx 역방향 프록시 구성: nginx 구성 파일 열기: sudonano/etc/nginx/nginx.conf 캐싱을 활성화하려면 http 블록에 다음 구성을 추가합니다. http{...proxy_cache_path /var/cache/nginxlevels=1:2keys_zone=my_cache:10mmax_size=10ginactive=60muse_temp_path=off;proxy_cache

See all articles