Home  >  Article  >  Backend Development  >  Detailed introduction to php caching technology and php caching implementation code_PHP tutorial

Detailed introduction to php caching technology and php caching implementation code_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:11:00942browse

Some information, such as information that is often constant but can still change, is placed in the cache to speed up the display. This is very valuable. The so-called cache is generally understood to be some shared information stored on the server. It is between the server and the server. Same as life and death, we can specify the next update time when saving the cache, for example, it should be updated every 5 minutes

Data cache: The data cache mentioned here refers to the database query PHP cache mechanism, each access When entering a page, it will first detect whether the corresponding cached data exists. If it does not exist, it will connect to the database, obtain the data, and serialize the query results and save them to the file. In the future, the same query results will be directly obtained from the cache table or file. get.

The most widely used example is the search function of Discuz, which caches the result ID into a table and searches the cache table first when searching for the same keyword next time.

As a common method, when multiple tables are associated, generate an array and save the contents in the attached table to a field in the main table. When necessary, decompose the array. The advantage of this is that only one table can be read. , the disadvantage is that there will be many more steps to synchronize the two data. The database is always the bottleneck. Trading the hard disk for speed is the key point of this.

Page cache:

Every time you access a page, it will first detect whether the corresponding cached page file exists. If it does not exist, connect to the database, get the data, display the page and generate a cache at the same time. Page file, so that the page file will come into play the next time you visit. (Template engines and some common PHP caching mechanism classes on the Internet usually have this function)

Time-triggered cache:

Check whether the file exists and the timestamp is less than the set expiration time. If the file is modified If the timestamp is greater than the current timestamp minus the expiration timestamp, use the cache, otherwise update the cache.

Content-triggered caching:

Force the PHP cache mechanism to be updated when data is inserted or updated.

Static cache:

The static cache mentioned here refers to static, directly generating text files such as HTML or XML, and regenerating them when there are updates, which is suitable for pages that do not change much. , let’s not talk about it anymore.

The above content is a code-level solution. I directly CP other frameworks and am too lazy to change. The content is similar, it is easy to do, and can be used in several ways, but the following content is for the server End-end caching solutions, non-code level, require the cooperation of multiple parties to achieve

Memory caching:

Memcached is a high-performance, distributed memory object PHP caching mechanism system for Reduce database load and improve access speed in dynamic applications.

PHP buffer:

There are eaccelerator, apc, phpa, xcache. I won’t talk about these. Search a bunch of them and see for yourself. If you know there is such a thing, OK

MYSQL cache:

This is also considered non-code level. Classic databases use this method. Look at the running time below, 0.09xxx and the like
I will post it According to the part of my.ini modified by the guy in blue, the 2G MYISAM table can be around 0.05S. It is said that he has modified it for almost a year

Web cache based on reverse proxy:

Such as Nginx, SQUID, mod_proxy (apache2 and above are divided into mod_proxy and mod_cache)
Examples of NGINX

Use Google to find some PHP caching technology methods

Send me a PHP caching implementation , implements apc and file caching, and inherits Cache_Abstract to call third-party caching tools.
Refer to shindig’s cache class and apc.

Php code

 代码如下 复制代码
class CacheException extends Exception {}  
/**
* Cache abstract class
*/  
abstract class Cache_Abstract {  
    /**
* Read cache variable
* *
* @param string $key cache subscript
* @return mixed
*/  
    abstract public function fetch($key);  
      
    /**
* Cache variable
* *
* @param string $key cache variable subscript
* @param string $value cache variable value
* @return bool
*/  
    abstract public function store($key, $value);  
      
    /**
* Delete cache variable *
* @param string $key cache index
* @return Cache_Abstract
*/  
    abstract public function delete($key);  
      
    /**
* Clear (delete) all caches
*
* @return Cache_Abstract
*/  
    abstract public function clear();  
      
    /**
* Lock cache variable *
* @param string $key cache index
* @return Cache_Abstract
*/  
    abstract public function lock($key);  
  
    /**
* Cache variable unlocking *
* @param string $key cache subscript*/  
    abstract public function unlock($key);  
  
    /**
* Get whether the cache variable is locked
* *
* @param string $key cache subscript
* @return bool
*/  
    abstract public function isLocked($key);  
  
    /**
* Make sure it is not locked
* Sleep at most $tries times to wait for unlocking, skip and unlock if timeout occurs
*
* @param string $key cache index
*/  
    public function checkLock($key) {  
        if (!$this->isLocked($key)) {  
            return $this;  
        }  
          
        $tries = 10;  
        $count = 0;  
        do {  
            usleep(200);  
            $count ++;  
        } while ($count <= $tries && $this->isLocked($key));  // 最多做十次睡眠等待解锁,超时则跳过并解锁  
  
        $this->isLocked($key) && $this->unlock($key);  
          
        return $this;  
    }  
}  
  
  
/**
* APC extended cache implementation
*
*
* @category Mjie
* @package Cache
* @author Liushui Mengchun
* @copyright Copyright (c) 2008-
* @license New BSD License
* @version $Id: Cache/Apc.php version number 2010-04-18 23:02 cmpan $
*/  
class Cache_Apc extends Cache_Abstract {  
      
    protected $_prefix = 'cache.mjie.net';  
      
    public function __construct() {  
        if (!function_exists('apc_cache_info')) {  
            throw new CacheException('apc extension didn't installed');  
        }  
    }  
      
    /**
* Save cache variable
* * @param string $key
* @param mixed $value
* @return bool
*/  
    public function store($key, $value) {  
        return apc_store($this->_storageKey($key), $value);  
    }  
      
    /**
* Read cache
* *
* @param string $key
* @return mixed
*/  
    public function fetch($key) {  
        return apc_fetch($this->_storageKey($key));  
    }  
      
    /**
* Clear cache
*
* @return Cache_Apc
*/  
    public function clear() {  
        apc_clear_cache();  
        return $this;  
    }  
      
    /**
* Delete cache unit
* *
* @return Cache_Apc
*/  
    public function delete($key) {  
        apc_delete($this->_storageKey($key));  
        return $this;  
    }  
      
    /**
* Whether the cache unit is locked
* *
* @param string $key
* @return bool
*/  
    public function isLocked($key) {  
        if ((apc_fetch($this->_storageKey($key) . '.lock')) === false) {  
            return false;  
        }  
          
        return true;  
    }  
      
    /** 
     * 锁定缓存单元 
     * 
     * @param string $key 
     * @return Cache_Apc 
     */  
    public function lock($key) {  
        apc_store($this->_storageKey($key) . '.lock', '', 5);  
        return $this;  
    }  
      
    /**
* Cache unit unlocked
* *
* @param string $key
* @return Cache_Apc
*/  
    public function unlock($key) {  
        apc_delete($this->_storageKey($key) . '.lock');  
        return $this;  
    }  
      
    /**
* Full cache name
* *
* @param string $key
* @return string
*/  
    private function _storageKey($key) {  
        return $this->_prefix . '_' . $key;  
    }  
}  
  
/**
* File cache implementation
*
*
* @category Mjie
* @package Cache
* @author Liushui Mengchun
* @copyright Copyright (c) 2008- < ;cmpan(at)qq.com>
* @license New BSD License
* @version $Id: Cache/File.php Version number 2010-04-18 16:46 cmpan $
*/  
class Cache_File extends Cache_Abstract {  
    public $useSubdir     = false;  
      
    protected $_cachesDir = 'cache';  
      
    public function __construct() {  
        if (defined('DATA_DIR')) {  
            $this->_setCacheDir(DATA_DIR . '/cache');  
        }  
    }  
      
    /**
* Get cached file
* *
* @param string $key
* @return string
*/  
    protected function _getCacheFile($key) {  
        $subdir = $this->useSubdir ? substr($key, 0, 2) . '/' : '';  
        return $this->_cachesDir . '/' . $subdir . $key . '.php';  
    }  
  
    /**
* Read cache variables
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @param string $ key cache index
* @return mixed
*/  
    public function fetch($key) {  
        $cacheFile = self::_getCacheFile($key);  
        if (file_exists($cacheFile) && is_readable($cacheFile)) {  
            // include 方式  
            //return include $cacheFile;  
            // 系列化方式  
  
            return unserialize(@file_get_contents($cacheFile, false, NULL, 13));  
        }  
  
        return false;  
    }  
  
    /**
* Cache variable
* To prevent information leakage, the cache file format is a php file and starts with ""
*
* @param string $key cache Variable subscript
* @param string $value The value of the cache variable
* @return bool
*/  
    public function store($key, $value) {  
        $cacheFile = self::_getCacheFile($key);  
        $cacheDir  = dirname($cacheFile);  
  
        if(!is_dir($cacheDir)) {  
            if(!@mkdir($cacheDir, 0755, true)) {  
                throw new CacheException("Could not make cache directory");  
            }  
        }  
    // 用include方式  
        //return @file_put_contents($cacheFile, '  
        return @file_put_contents($cacheFile, '' . serialize($value));  
    }  
  
    /**
* Delete cache variable *
* @param string $key cache subscript
* @return Cache_File
*/  
    public function delete($key) {  
        if(emptyempty($key)) {  
            throw new CacheException("Missing argument 1 for Cache_File::delete()");  
        }  
          
        $cacheFile = self::_getCacheFile($key);  
        if(!@unlink($cacheFile)) {  
            throw new CacheException("Cache file could not be deleted");  
        }  
  
        return $this;  
    }  
  
    /**
* Whether the cache unit has been locked
* *
* @param string $key
* @return bool
*/  
    public function isLocked($key) {  
        $cacheFile = self::_getCacheFile($key);  
        clearstatcache();  
        return file_exists($cacheFile . '.lock');  
    }  
  
    /** 
     * 锁定 
     * 
     * @param string $key 
     * @return Cache_File 
    */  
    public function lock($key) {  
        $cacheFile = self::_getCacheFile($key);  
        $cacheDir  = dirname($cacheFile);  
        if(!is_dir($cacheDir)) {  
            if(!@mkdir($cacheDir, 0755, true)) {  
                if(!is_dir($cacheDir)) {  
                    throw new CacheException("Could not make cache directory");  
}                                                                                                             ;
}

/** 
     * 解锁 
     * 
     * @param string $key 
     * @return Cache_File 
    */
public function unlock($key) {
$cacheFile = self::_getCacheFile($key);
@unlink($ cacheFile . '.lock');
return





http://www.bkjia.com/PHPjc/444684.html
www.bkjia.com

true

TechArticleSome information, such as information that often remains unchanged but can still change, is placed in the cache to speed up display. This It is very valuable. The so-called cache, the popular understanding is that some data are stored on the server side...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn