Php cache file technology-PHP source code

Source: Internet
Author: User
The following describes three cache file Methods: fastcgi_cache and proxy_cache under nginx, memcache, and PHP File Cache. The following describes three cache file Methods: fastcgi_cache and proxy_cache under nginx, memcache, and PHP File Cache.

Script ec (2); script

Nginx has two caching mechanisms: fastcgi_cache and proxy_cache.
Let's talk about the differences between the two cache mechanisms.
Proxy_cache is used to cache the content of backend servers. It may be any content, including static and dynamic content.
Fastcgi_cache is used to cache the content generated by fastcgi. In many cases, it is the dynamic content generated by php.
The proxy_cache cache reduces the number of communications between nginx and the backend, saving the transmission time and backend bandwidth.
Fastcgi_cache reduces the number of communications between nginx and php, and reduces the pressure on php and databases.

Proxy_cache cache settings
# Note: The paths specified by proxy_temp_path and proxy_cache_path must be in the same partition.
Proxy_temp_path/data0/proxy_temp_dir;
# Set the name of the Web cache area to cache_one. The size of the memory cache space is 200 MB. The content not accessed within one day is automatically cleared. The size of the hard disk cache space is 30 GB.
Proxy_cache_path/data0/proxy_cache_dir levels = keys_zone = cache_one: 200 m inactive = 1d max_size = 30g;

The Code is as follows:

Server
{
Listen 80;
Server_name www.yourdomain.com 192.168.8.42;
Index index.html index.htm;
Root/data0/htdocs/www;

Location/
{
# If the backend server returns errors such as 502, 504, and execution timeout, the request is automatically forwarded to another server in the upstream Server Load balancer pool for failover.
Proxy_next_upstream http_502 http_504 error timeout invalid_header;
Proxy_cache cache_one;
# Set different cache times for different HTTP Status Codes
Proxy_cache_valid 200 304 12 h;
# Combine domain names, Uris, and parameters into the Key values of the Web cache. Nginx hashes the cached content to the second-level cache directory based on the Key values.
Proxy_cache_key $ host $ uri $ is_args $ args;
Proxy_set_header Host $ host;
Proxy_set_header X-Forwarded-For $ remote_addr;
Proxy_pass http: // backend_server;
Expires 1d;
}

# It is used to clear the cache. If a URL is http: // 192.168.8.42/test.txt, you can clear the cache of the URL by accessing http: // 192.168.8.42/purge/test.txt.
Location ~ /Purge (/.*)
{
# Only the specified IP address or IP segment is allowed to clear the URL cache.
Allow 127.0.0.1;
Allow 192.168.0.0/16;
Deny all;
Proxy_cache_purge cache_one $ host $1 $ is_args $ args;
}

# Dynamic applications whose extensions end with. php,. jsp, And. cgi are not cached.
Location ~ . *. (Php | jsp | cgi )? $
{
Proxy_set_header Host $ host;
Proxy_set_header X-Forwarded-For $ remote_addr;
Proxy_pass http: // backend_server;
}

Access_log off;
}
}


Fastcgi_cache cache settings
# Define the cached folder

The Code is as follows:
Fastcgi_cache_path/tt/cache levels = keys_zone = NAME: 2880 m inactive = 2d max_size = 10G;

# Define cache for different url requests

The Code is as follows:
Fastcgi_cache_key "$ scheme $ request_method $ host $ uri $ arg_filename $ arg_x $ arg_y ";

Server {
Listen 8080;
Server_name www. example. com;
Location /{
Root/www;
Index index.html index.htm index. php;
}

Location ~ (|. Php) $ {
Root/www;
Fastcgi_pass 127.0.0.1: 9000;

Fastcgi_cache NAME;
Fastcgi_cache_valid 200 48 h;
Fastcgi_cache_min_uses 1;
Fastcgi_cache_use_stale error timeout invalid_header http_500;

Fastcgi_index index. php;
Fastcgi_param SCRIPT_FILENAME/scripts $ fastcgi_script_name;
Include fastcgi. conf;
# The cookie cannot be obtained when the cache is set. You need to define this sentence after checking.
Fastcgi_pass_header Set-Cookie;
}

Log_format access' $ remote_addr-$ remote_user [$ time_local] "$ request "'
'$ Status $ body_bytes_sent "$ http_referer "'
'"$ Http_user_agent" $ http_x_forwarded_for ';
Access_log/httplogs/access. log access;
}

In general, the proxy_cache configuration of nginx is similar to that of fastcgi_cache.

--------------------------------------------------------------------------------

Memcache Cache
Before discussing the memcache cache, let's take a look at the mysql memory cache.
The memory cache of mysql can be specified in my. cnf: the memory table is different from the temporary table, and the temporary table is also in memory. The maximum memory of the temporary table must be set through tmp_table_size = m. When the maximum value of the temporary table is queried, it is automatically converted to a disk table. In this case, the performance will be greatly reduced due to IO operations, but the memory table will not. When the memory is full, A message indicating full data error is displayed.
Example:

The Code is as follows:
Create table test
(
Id int unsigned not null auto_increment primary key
State char (10 ),
Type char (20 ),
Date char (30)
) Engine = memory default charset = utf8

Memory table features:
1. The memory table is defined to be stored on the disk. The extension is. frm, so it will not be lost after restart.
2. Data in the memory table is stored in the memory, and data will be lost after restart.
3. Memory tables use a fixed length format
4. The memory table does not support blob or text columns. For example, the varchar and text fields are not supported.
5. The memory table supports the auto_increment column and the index of a column that can contain null values.
6. Memory tables do not support transactions
7. The memory table is a table lock. When the modification is frequent, the performance may decrease.

Share a php cache class

The Code is as follows:

Class Cache
{

Private static $ _ instance;
Protected $ _ cacheId = null;

Const CLEANING_MODE_ALL = 'all ';
Const CLEANING_MODE_OLD = 'old ';

Protected $ _ options = array (
'Cache _ dir' => null, // data cache directory
'Life _ time' => 7200, // Cache time
'Page _ dir' => null, // text cache directory
'Cache _ prefix' => 'cache _ '// cache prefix
);

Private function _ construct (){}

// Create the _ clone method to prevent objects from being copied and cloned.
Private function _ clone (){}

/**
* Get the cache object. If there is a direct return, if there is no instantiation itself
* @ Return object cache
*/
Public static function getInstance (){

If (! Self: $ _ instance ){

Self: $ _ instance = new self ();
}

Return self: $ _ instance;
}

/**
* Set cache Parameters
* @ Param array $ options indicates the cache parameter set to be set.
*/
Public function setOptions ($ options = array ()){

While (list ($ name, $ value) = each ($ options )){
$ This-> setOption ($ name, $ value );
}
}

/**
* Get the current cache parameter. If $ name is null, all parameters are returned. Otherwise, this parameter value is returned.
* @ Param string $ name: name of the parameter to be returned
* @ Return string or array $ option;
*/
Public function getOption ($ name = null ){

If (null ===$ name)
Return $ this-> _ options;

If (! Is_string ($ name )){
ThrowException ("Incorrect Parameter name: $ name ");
}

If (array_key_exists ($ name, $ this-> _ options )){
Return $ this-> _ options [$ name];
}
}

/**
* Set cache Parameters
* @ Param array $ options the cache parameter to be set
*/
Protected function setOption ($ name, $ value ){

If (! Is_string ($ name )){
ThrowException ("Incorrect Parameter name: $ name ");
}
$ Name = strtolower ($ name );
If (array_key_exists ($ name, $ this-> getOption ())){
$ This-> _ options [$ name] = $ value;
}

If ($ this-> _ options ['cache _ dir'] = null ){
$ This-> setOption ('cache _ dir', $ this-> getTmpDir (). DIRECTORY_SEPARATOR );
}

If ($ this-> _ options ['page _ dir'] = null ){
$ This-> setOption ('page _ dir', $ this-> getTmpDir (). DIRECTORY_SEPARATOR );
}
}

/**
* Read data cache. If it does not exist or expires, false is returned.
* @ Param string $ id cache ID
* @ Return false or data
*/
Public function load ($ id ){

$ This-> _ cacheId = $ id;
$ File = $ this-> getOption ('cache _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;

If (@ filemtime ($ file)> = time ()){

Return unserialize (file_get_contents ($ file ));
} Else {
@ Unlink ($ file );
Return false;
}
}

/**
* Save the data cache and set the cache expiration time
* @ Param array or string $ data the data to be cached
* @ Param int $ lifeTime cache expiration time
*/
Public function save ($ data, $ lifeTime = null ){

If (null! ==$ LifeTime)
$ This-> setOption ('life _ time', $ lifeTime );

$ File = $ this-> getOption ('cache _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;
$ Data = serialize ($ data );
@ File_put_contents ($ file, $ data );
@ Chmod ($ file, 0777 );
@ Touch ($ file, time () + $ this-> getOption ('life _ time']);
}

/**
* Read the output cache. If the cache does not exist or expires, the output cache will be restarted.
* @ Param string $ id cache ID
*/
Public function start ($ id ){

$ This-> _ cacheId = $ id;
$ File = $ this-> getOption ('page _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;

If (@ filemtime ($ file)> = time ()){

Return file_get_contents ($ file );
} Else {
@ Unlink ($ file );
Ob_start ();
Return false;
}
}

/**
* Delete the specified ID cache.
* @ Param string $ id cache ID
*/
Public function remove ($ id ){

$ This-> _ cacheId = $ id;
// Delete the data cache with the matching conditions
$ File = $ this-> getOption ('cache _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;
@ Unlink ($ file );
// Delete the output cache with the matching conditions
$ File = $ this-> getOption ('page _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;
@ Unlink ($ file );
}

/**
* Save the output cache and set the cache expiration time
* @ Param int $ lifeTime cache expiration time
*/
Public function end ($ lifeTime = null ){

If (null! ==$ LifeTime)
$ This-> setOption ('life _ time', $ lifeTime );

$ File = $ this-> getOption ('page _ dir'). $ this-> getOption ('cache _ prefix'). $ this-> _ cacheId;
$ Data = ob_get_contents ();
Ob_end_clean ();
@ File_put_contents ($ file, $ data );
@ Chmod ($ file, 0777 );
@ Touch ($ file, time () + $ this-> getOption ('life _ time']);
}

/**
* Clear the corresponding cache based on parameters
* @ Param string $ mode cache type, including (CLEANING_MODE_ALL: All caches, CLEANING_MODE_OLD: expired caches)
*/
Public function clear ($ mode = CLEANING_MODE_OLD ){

$ Dirs = array ('cache _ dir', 'page _ dir ');
Foreach ($ dirs as $ value ){
If (null! = $ This-> getOption ($ value )){
$ Files = scandir ($ this-> getOption ($ value ));
Switch ($ mode ){

Case CLEANING_MODE_ALL:
Default:
Foreach ($ files as $ val ){
@ Unlink ($ this-> getOption ($ value). $ val );
}
Break;

Case CLEANING_MODE_OLD:
Default:
Foreach ($ files as $ val ){
If (filemtime ($ this-> getOption ($ value). $ val) <time ()){
@ Unlink ($ this-> getOption ($ value). $ val );
}
}
Break;
}
}
}
}

/**
* Use a temporary folder as the cache folder.
* @ Return $ dir Temporary Folder path
*/
Public function getTmpDir (){

$ Tmpdir = array ();
Foreach (array ($ _ ENV, $ _ SERVER) as $ tab ){
Foreach (array ('tmpdir', 'temp ', 'tmp', 'windir', 'systemroot') as $ key ){
If (isset ($ tab [$ key]) {
If ($ key = 'windir') or ($ key = 'systemroot ')){
$ Dir = realpath ($ tab [$ key]. '\ temp ');
} Else {
$ Dir = realpath ($ tab [$ key]);
}
If ($ this-> _ isGoodTmpDir ($ dir )){
Return $ dir;
}
}
}
}
$ Upload = ini_get ('upload _ tmp_dir ');
If ($ upload ){
$ Dir = realpath ($ upload );
If ($ this-> _ isGoodTmpDir ($ dir )){
Return $ dir;
}
}
If (function_exists ('sys _ get_temp_dir ')){
$ Dir = sys_get_temp_dir ();
If ($ this-> _ isGoodTmpDir ($ dir )){
Return $ dir;
}
}
// Detect by creating a temporary file
$ TempFile = tempnam (md5 (uniqid (rand (), TRUE )),'');
If ($ tempFile ){
$ Dir = realpath (dirname ($ tempFile ));
Unlink ($ tempFile );
If ($ this-> _ isGoodTmpDir ($ dir )){
Return $ dir;
}
}
If ($ this-> _ isGoodTmpDir ('/tmp ')){
Return '/tmp ';
}
If ($ this-> _ isGoodTmpDir ('\ temp ')){
Return '\ temp ';
}
Throw new Exception ('the temporary directory cannot be determined. Please manually specify cache_dir ', E_USER_ERROR );
}

/**
* Verify that the given temporary directory is readable and writable.
*
* @ Param string $ dir Temporary Folder path
* @ Return boolean true or false whether the Temporary Folder path can be read and written
*/
Protected function _ isGoodTmpDir ($ dir ){

If (is_readable ($ dir )){
If (is_writable ($ dir )){
Return true;
}
}
Return false;
}


} // Endclass

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.