Home  >  Article  >  Backend Development  >  PHP APC cache configuration and usage details_PHP tutorial

PHP APC cache configuration and usage details_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:37:10850browse

1. Introduction to APC cache
APC, the full name is Alternative PHP Cache, and the official translation is called "Optional PHP Cache". It provides us with a framework for caching and optimizing PHP's intermediate code. APC's cache is divided into two parts: system cache and user data cache.
System caching
It means that APC caches the compilation results of the PHP file source code, and then compares the time stamps every time it is called. If not expired, the cached intermediate code is used to run. Default cache
3600s (one hour). But this still wastes a lot of CPU time. Therefore, you can set the system cache in php.ini to never expire (apc.ttl=0). However, if you set it up like this, you need to restart the WEB server after changing the PHP code. Currently, this type of cache is commonly used.
User data cache
The cache is read and written by the user using the apc_store and apc_fetch functions when writing PHP code. If the amount of data is not large, you can give it a try. If the amount of data is large, it would be better to use a more specialized memory caching solution like memcache
Cache key generation rules
Each slot in the APC cache will have a key, and the key is
apc_cache_key_t For structure types, in addition to key-related attributes, the key is the generation of the h field. The h field determines where in the slots array this element falls. The generation rules are different for user cache and system cache. The user cache generates keys through the apc_cache_make_user_key function. The key string passed in by the user relies 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 generates keys through the apc_cache_make_file_key function. Different solutions can be treated differently through the switch of the APC configuration item apc.stat. When turned on, that is,
apc.stat= On, the compiled content will be automatically recompiled and cached if updated. The h value at this time is the value obtained by adding the device and inode of the file. In the case of shutdown, that is, when apc.stat=off, when the file is modified, if you want the updated content to take effect, you must restart the web server. At this time, the h value is generated based on the path address of the file, and the path here is an absolute path. Even if you use a relative path, the PG (include_path) location file will be searched to obtain the absolute path, so using an absolute path will skip the check and improve the efficiency of the code.
Add cache process
Taking 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 will generate the key based on this string. If the key parameter is an array, APC will traverse the entire array and generate the key. Based on these keys, APC will call _apc_store to store the value in the cache. Since this is a user cache, the cache currently used is apc_user_cache. It is the apc_cache_make_user_entry function that performs the write operation, which ultimately calls apc_cache_user_insert to perform the traversal query and write operation. Correspondingly, the system cache uses apc_cache_insert to perform write operations, which will eventually call _apc_cache_insert.
Whether it is user cache or system cache, the general execution process is similar. The steps are as follows:

Locate the position of the current key in the slots array through the remainder operation: cache->slots[key.h % cache->num_slots];
After locating the position in the slots array, traverse The slot linked list corresponding to the current key. If the key of the slot matches the key to be written or the slot expires, the current slot is cleared.
Insert a new slot after the last slot.
2. APC module installation

A. Install APC under WINDOWS
Step one: Download php_apc.dll at http://pecl.php.net/package/ To correspond to the php version of apc, put php_apc.dll into your ext directory
Step 2: Make php.ini support the apc extension module. Then open php.ini and add:

Copy the code The code is as follows:
extension=php_apc.dll
apc.rfc1867 = on
apc.max_file_size = 100M
upload_max_filesize = 100M
post_max_size = 100M
//The above parameters can be defined by yourself

Step 3: Check whether PHP APC apc_store apc_fetch is supported
Check if there are apc related items in phpinfo

Installing APC under B.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:

Copy the code The code is as follows:

extension = "apc.so" ;
;APC setting
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 64M
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 there are apc related items in phpinfo
3. Configuration Detailed explanation of parameters and summary of use
1). Detailed explanation of parameter configuration of APC module

Copy code Code 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, since there is no other way to disable it (when compiling as DSO, the extension line in php.ini can be 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 try to increase the value of this parameter.

apc.shm_size integer
The size of each shared memory block is in MB. By default, some systems (including most BSD variants) have very low shared memory block size limits.

apc.optimization integer
optimization level. Set to 0 to disable optimization, higher values ​​use more powerful optimizations. Expect modest speed improvements. This is still experimental in nature.

apc.num_files_hint integer
Hint for the number of different source files included and requested on your web server. If you are unsure, set it to 0 or omit it; this setting is likely to be useful primarily on sites with thousands of source files.

apc.ttl Integer
When a cache entry is needed by another entry in the cache area, what we need to consider is the number of seconds this cache entry is allowed to be idle in the cache area. Setting this parameter to 0 means that your cache may be filled with stale entries, and new entries will not be cached.

apc.gc_ttl Integer
Number of seconds for cache entries to live in the garbage collection list. This value provides error protection in the event that a cached source file is executed and the server process dies at the same time. If that source file is modified, the memory allocated to the old version of the cache entry will not be reclaimed until the TTL value set by this parameter is reached. Setting it to 0 disables this feature.

apc.cache_by_default Boolean
Defaults to On, but can be set to Off and used with apc.filters starting with a plus sign. Files will only be cached if they match the filter.

apc.filters String
A comma-separated list of POSIX extended regular expressions. If any pattern matches the source file name, the file will not be cached. Note that the file name used to match is the file name passed to include/require, not the absolute path. If the first character of the regular expression is + , then the expression means that any file matching the expression will be cached, if the first character is - then any matches will not be cached. - is the default value, so can be omitted.

apc.mmap_file_mask string (I really don’t understand this paragraph, so there is no translation)
If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining 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 a .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 a service or modify a file, you will end up with multiple processes trying to cache the same file at the same time. File competition. This option sets the percentage at which the process skips attempts to cache an uncached file. Or think of this as the probability of a single process skipping the cache. For example, setting apc.slam_defense to 75 means that the process has a 75% chance of not caching uncached files. Therefore, the higher the setting, the more likely it is to reduce the cache collision probability. Set to 0 to disable this feature.

apc.file_update_protection integer
When you modify a file on a running server, you should perform atomic operations. That is, write a temporary file first, and then rename (mv) the file to its final location when finished. Many text editors, cp, tar and some other similar programs do not operate this way. This means there is an opportunity to access and (cache) the file while the file is still being written. The setting of apc.file_update_protection causes the cache to delay marking new files. The default value is 2, which means that if the modification time of the file is found to be less than 2 seconds from the access time, the file will not be cached. Unlucky users who access a half-written file will see bizarre behavior, but at least it's not persistent. If you are sure that you frequently use atomic operations to update your files, you can turn off this protection by setting this parameter to 0. If your system is flooded with IO operations and causing the update process to take more than 2 seconds, you may need to increase this value.

apc.enable-cli Integer
mostly for testing and debugging. Enable the APC function for the CLI version of PHP.Generally speaking, you wouldn't think of creating, porting, and discarding APC's cache for every CLI request, but for various testing situations, it's easy enough to turn on APC for the CLI version.

2). Usage summary
1. Use the Spinlocks lock mechanism to achieve the best performance.
2. APC provides apc.php for monitoring and managing APC cache. Don’t forget to change the administrator name and password
3. APC creates shared memory through mmap anonymous mapping by default, and cache objects are stored in this "large" memory space. The shared memory is managed by APC itself
4. We need to adjust the values ​​​​of apc.shm_size, apc.num_files_hints, and apc.user_entries_hint through statistics. Until the optimal
5, okay, I admit that apc.stat = 0 can get better performance. Whatever you want me to do is acceptable.
6. PHP predefined constants, you can use the apc_define_constants() function. However, according to APC developers, pecl hidef has better performance. Just throw out define, which is inefficient.
7. Function apc_store(). For PHP variables such as system settings, the life cycle is the entire application (from the httpd daemon until the httpd daemon is closed). It is better to use APC than Memcached. After all, do not use the network transmission protocol tcp.
8. APC is not suitable for caching frequently changed user data through the function apc_store(), and some strange phenomena will occur.

4. Usage examples
The following references the APC cache class of the initphp framework

Copy the code The code is as follows:

if
class Apc{

/**
* Apc cache - set cache
* Set cache key, value and cache time
* @param string $key KEY value
* @param string $value value
* @param string $ time cache time
*/
public function set_cache($key, $value, $time = 0) {
if ($time == 0) $time = null; //Cache permanently in case of null
return apc_store($key, $value, $time);;
}

                                                                                                                                                                                                                                          . >*/
public function clear($key) {
return apc_delete($key);
}

/**
* Apc cache - Get cache
* Get cache data through KEY
* @param string $key KEY value
*/
public function clear_all() {
apc_clear_cache('user'); // Clear user cache
return apc_clear_cache(); // Clear cache
}

/**
* Apc cache - clear a cache
* Delete a cache from memcache
* @param string $key KEY value
*/
public Function Exists ($ Key) {
Return APC_EXISTS ($ key);
}

/ **
* Apc cache - clear all caches
* This feature is not recommended
* @return
* /
Public function inc ($ key, $ STEP) {
                                                                                                                                            """"""""""""""" return apc_dec($key, (int) $step);
}

/**
* Check if APC cache exists
* @param string $key KEY value
*/
public function info() {
return apc_cache_info();
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/736793.htmlTechArticle1. Introduction to APC Cache APC, the full name is Alternative PHP Cache, and the official translation is called "Optional PHP Cache". It provides us with a framework for caching and optimizing PHP's intermediate code. APC’s cache score...
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