PHPAPC cache configuration and usage

Source: Internet
Author: User
Tags apc apc module
This article describes in detail the introduction, parameter configuration, installation steps, and usage of the PHPAPC module. some of the content is translated from PHPManual and may be incomplete. I hope you can correct me. 1. APC cache overview
APC, full name: Alternative PHP Cache, officially translated as "optional PHP Cache ". It provides us with a framework for caching and optimizing PHP intermediate code. APC cache consists of system cache and user data cache.
System cache
It indicates that APC caches the compilation results of the PHP file source code and compares the time mark for each call. If it does not expire, it runs with the cached intermediate code. Default cache
3600 s (one hour ). However, this will still waste a lot of CPU time. Therefore, you can set the system cache in php. ini to never expire (apc. ttl = 0 ). However, you need to restart the WEB server after the php code is modified. This type of cache is usually used.
User data cache
The cache is read and written by users using the apc_store and apc_fetch functions when writing PHP code. If the data volume is small, you can try it. If the data volume is large, it would be better to use a more specific memory cache solution similar to memcache.
Cache key generation rules
Each slot in the APC cache has a key, and the key is
Apc_cache_key_t struct type. apart from key-related attributes, the key is the generation of the h field. The h field determines where the element falls in the slots array. User cache and system cache have different generation rules. The user cache uses the apc_cache_make_user_key function to generate a key. The key string passed by the user depends on the hash function in the PHP kernel (the hash function used by PHP's hashtable: zend_inline_hash_func) to generate the h value.
The system cache uses the apc_cache_make_file_key function to generate a key. Different solutions are treated differently through the APC. stat switch, which is the configuration item of apc. When enabled, that is
If apc. stat = On is updated, the compiled content is automatically re-compiled and cached. The h value is the value obtained by adding the device and inode of the file. When apc. stat = off is disabled, the Web server must be restarted to make the updated content take effect after the file is modified. In this case, the h value is generated based on the file path address, and the path here is the absolute path. Even if you are using a relative path, you will also find the PG (shortde_path) location file to get the absolute path. Therefore, using the absolute path will skip the check, which can improve the code efficiency.
Add cache process
Taking the user cache as an example, the apc_add function is used to add content to the APC cache. If the key parameter is a string, APC generates a key based on the string. if the key parameter is an array, APC traverses the entire array to generate a key. Based on these keys, APC will call _ apc_store to store values in the cache. Because this is the user cache, the current cache is apc_user_cache. The write operation is the apc_cache_make_user_entry function, which finally calls apc_cache_user_insert to perform traversal query and write operations. Correspondingly, when the system cache uses apc_cache_insert to execute the write operation, it will eventually call _ apc_cache_insert.
The execution process is similar to that of the user cache or system cache. The steps are as follows:

Perform the remainder operation to locate the location of the current key in the slots array: cache-> slots [key. h % cache-> num_slots];
After locating the slots array, traverse the slot linked list corresponding to the current key. if the slot key matches the key to be written or the slot expires, clear the current slot.
Insert a new slot after the last slot.
II. installation of APC module

A. install APC in WINDOWS
Step 1: Download php_apc.dll in the http://pecl.php.net/package/apc to correspond to the php version to put php_apc.dll into your ext Directory
Step 2: Let php. ini support the apc extension module. Then open php. ini and add:
The code is as follows: extension = php_apc.dll
Apc. rfc1867 = on
Apc. max_file_size = 100 M
Upload_max_filesize = 100 M
Post_max_size = 100 M
// You can customize the preceding parameters.

Step 3: Check whether php apc apc_store apc_fetch is supported
Check whether apc related items exist in phpinfo.

B. install APC in LIUNX
Step 1: Download and Install
Wget http://pecl.php.net/get/APC-3.1.8.tgz
Tar-zxvf APC-3.1.8.tgz cd APC-3.1.8
/Usr/local/php/bin/phpize
. /Configure -- enable-apc -- enable-mmap -- enable-apc-spinlocks -- disable-apc-pthreadmutex -- with-php-config =/usr/local/php/bin/php- config
Make
Sudo make install
Step 2: Configure APC
Add the following configuration items to/usr/local/php/etc/php. ini:
The code is as follows:
Extension = "apc. so ";
; APC setting
Apc. enabled = 1
Apc. shm_segments = 1
Apc. shm_size = 64 M
Apc. optimization = 1
Apc. num_files_hint = 0
Apc. ttl = 0
Apc. gc_ttl = 3600
Apc. cache_by_default = on
Step 3: Check whether the installation is successful
Restart apache or/usr/local/php/sbin/php-fpm restart
Check whether apc related items exist in phpinfo.
III. configuration parameters and usage summary
1) details about parameters of the APC module

The code is as follows:
Apc. enabled Boolean
Apc. enabled can be set to 0 to disable APC. This is mainly useful. When APC is statically compiled into PHP, it is disabled because there is no other method (when it is compiled into DSO, php can be used. the extension line in ini is commented out ).

Apc. shm_segments integer
The number of shared memory blocks allocated to the compilation cache. If APC runs out of shared memory and you have set apc. shm_size to the maximum value allowed by the system, you can increase the value of this parameter.

Apc. shm_size integer
The size of each shared memory block is measured in MB. By default, the size of shared memory blocks in some systems (including most BSD variant systems) is very low.

Apc. optimization integer
Optimization level. If it is set to 0, optimization is disabled. the higher the value, the more powerful the optimization is. We are looking forward to improvement in speed. This is experimental.

Apc. num_files_hint integer
The number of source files that are included and requested on your Web server. If you are not sure, set it to 0 or omitted. this setting may be mainly used for sites with thousands of source files.

Apc. ttl integer
When a cache entry is required by another entry in the cache area, we need to consider the number of seconds that the cache entry can be idle in the cache area. Setting this parameter to 0 means that your cache may be filled with fresh entries, and new entries cannot be cached.

Apc. gc_ttl integer
The number of seconds that a cache entry will survive in the garbage collection list. This value provides error protection when executing a cache source file while the server process is dead. If the source file is modified, the cache entries allocated to the old version of the memory will not be recycled until the TTL value set by this parameter reaches. Setting 0 is to disable this feature.

Apc. cache_by_default Boolean type
The default value is On, but it can be set to Off and used with apc. filters starting with the plus sign. the file is cached only when the filter is matched.

Apc. filters string
A list of POSIX extension regular expressions separated by commas. If any mode matches the source file name, the file will not be cached. Note that the file name used for matching is the file name passed to include/require, rather than the absolute path. If the first character of the regular expression is +, the expression means that any file that matches the expression will be cached. if the first character is-, no matching will be cached. -Is the default value, so it can be omitted.

Apc. mmap_file_mask string)
If compiled with MMAP support by using -- enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap 'ed memory region is going to be file-backed or shared memory backed. for straight file-backed mmap, set it to something like/tmp/apc. XXXXXX (exactly 6 Xs ). to use POSIX-style shm_open/mmap put. shm somewhere in your mask. e.g. /apc. shm. XXXXXX You can also set it to/dev/zero to use your kernel's/dev/zero interface to anonymous mmap 'ed memory. leaving it undefined will force an anonymous mmap.

Apc. slam_defense integer
On a very busy server, whether you start the service or modify files, you will cause a multi-process to try to cache the competition for the same file at the same time. This option sets the percentage of files that the process skips and tries to cache. Or you can think of this as the probability that a separate process will skip the cache. For example, setting apc. slam_defense to 75 means that the process has a 75% chance of not caching files that are not cached. Therefore, the higher the setting, the more likely the cache collision rate can be reduced. If it is set to 0, this feature is disabled.

Apc. file_update_protection integer
When you modify a file on a running server, you should perform atomic operations. That is, first write a temporary file, and then rename the file (mv) to its final location. Many text editors, cp, tar, and other similar programs do not perform this operation. This means that you have the opportunity to access (cache) the file while it is still being written. The apc. file_update_protection setting causes the cache to mark the delay of new files. The default value is 2, which means that the file will not be cached if the modification time of the file is less than 2 seconds from the access time. Unfortunately, users who access half of the files they write will see a strange situation, but at least this is not continuous. If you are sure that you often use atomic operations to update your files, you can disable this protection by setting this parameter to 0. If your system is full of io operations and it takes more than 2 seconds to update the program, you may need to increase the value.

Apc. enable-cli integer
Mostly for testing and debugging. Enable the APC function for PHP in the CLI version. In general, you will not expect to create, port, or discard the APC cache for each CLI request, but it is easy to enable APC for the CLI version in various test cases.

2). usage summary
1. use the Spinlocks lock mechanism to achieve optimal performance.
2. APC provides apc. php for monitoring and managing the APC cache. Do not forget to change the administrator name and password
3. by default, APC creates shared memory through mmap anonymous ing, and cache objects are stored in this "large" memory space. APC manages the shared memory
4. we need to adjust the values of apc. shm_size, apc. num_files_hints, and apc. user_entries_hint through statistics. Until the best
5. well, I admit that apc. stat = 0 can achieve better performance. Everything I want to do is acceptable.
6. PHP pre-defined constants. you can use the apc_define_constants () function. However, according to APC developers, the performance of pecl hidef is better, and define is inefficient.
7. the apc_store () function. for PHP variables such as system settings, the life cycle is the whole application (from the httpd daemon process to the httpd daemon). APC is better than Memcached. It must not pass through the network transmission protocol tcp.
8. APC is not suitable for caching user data that frequently changes through the apc_store () function, and some strange phenomena may occur.

4. use instances
The APC cache class of the initphp framework is referenced below
The code is as follows:
If
Class Apc {

/**
* Apc cache-set cache
* Set the cache key, value, and cache time.
* @ Param string $ key KEY value
* @ Param string $ value
* @ Param string $ time cache time
*/
Public function set_cache ($ key, $ value, $ time = 0 ){
If ($ time = 0) $ time = null; // permanent cache when null
Return apc_store ($ key, $ value, $ time );;
}


/**
* Apc cache-get cache
* Obtain cache data using the KEY
* @ Param string $ key KEY value
*/
Public function get_cache ($ key ){
Return apc_fetch ($ key );
}

/**
* Apc cache-clear a cache
* Delete a cache from memcache
* @ Param string $ key KEY value
*/
Public function clear ($ key ){
Return apc_delete ($ key );
}

/**
* Apc cache-clear all caches
* This function is not recommended.
* @ Return
*/
Public function clear_all (){
Apc_clear_cache ('user'); // clear the user cache
Return apc_clear_cache (); // clear cache
}

/**
* Check whether the APC cache exists.
* @ Param string $ key KEY value
*/
Public function exists ($ key ){
Return apc_exists ($ key );
}

/**
* Field auto-increment-used for counting
* @ Param string $ key KEY value
* @ Param int $ step the new step value
*/
Public function inc ($ key, $ step ){
Return apc_inc ($ key, (int) $ step );
}

/**
* Field auto-subtraction-used for counting
* @ Param string $ key KEY value
* @ Param int $ step the new step value
*/
Public function dec ($ key, $ step ){
Return apc_dec ($ key, (int) $ step );
}

/**
* Return APC cache information
*/
Public function info (){
Return apc_cache_info ();
}
}

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.