PHP APC Cache configuration, use detailed

Source: Internet
Author: User
Tags anonymous apc apc configuration apc module garbage collection hash php file php code

  This article introduces the introduction of the PHP APC module, parameter configuration, installation steps, use examples, because some of the content is translated from the PHP manual, there may be a lack of comprehensive place. I hope you will be correct.

First, APC cache introduction APC, full name is alternative PHP cache, official translation is called "Optional PHP Caching." It provides us with a framework for caching and optimizing PHP's intermediate code. The APC cache is divided into two parts: the system cache and the user data cache. System caching it means that the APC caches the compiled results of the PHP file source code, and then compares the time tag with each call. If it is not expired, it is run using the cached intermediate code. Default Cache  3600s (one hour). But it still wastes a lot of CPU time. Therefore, you can set the system cache to never expire (apc.ttl=0) in php.ini. However, if you do this, you need to restart the Web server after you change the PHP code. This type of caching is currently used more often. User data cache caching is read and written by the user when writing PHP code using Apc_store and Apc_fetch function operations. If the amount of data is small, you can try. If the volume of data is large, using more monographs like memcache memory caching scheme will better cache the key generation rule APC's cache each slot will have a key,key is the  apc_cache_key_t struct type, in addition to key-related attributes, The key is the generation of the H field. The H field determines which position this element falls in the slots array. The generation rules for user caching and system caching are different. User caching generates key 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 the PHP Hashtable: zend_inline_hash_func) to generate H values. The system cache generates key through the Apc_cache_make_file_key function. Different scenarios are differentiated by the apc.stat switches of the APC configuration item. When opened, that is,  apc.stat= on, the compiled content is automatically recompiled and cached if updated. The H value at this time is the value of the device of the file and the addition of the inode. In the case of shutdown, that is, when the file is modified, the Web server must be restarted if you want the updated content to take effect Apc.stat=off. At this point the H value is generated from the path address of the file, and the path here is an absolute path. Even if you are using a relative path, you will find the PG (include_path) location file to get an absolute path, so skipping the check using an absolute path can improve the efficiency of your code. Adding caching procedures in the case of user caching, the Apc_add function is used to add content to the APC cache. If the key argument is a characterString, the APC generates key based on this string, and if the key argument is an array, the APC traverses the entire array and generates the key. According to these KEY,APC, the _apc_store is called to store the value in the cache. Because this is a user cache, the cache currently in use is Apc_user_cache. The write operation is performed by the Apc_cache_make_user_entry function, which ultimately calls Apc_cache_user_insert to perform traversal queries and write operations. In this correspondence, the system cache performs a write operation using Apc_cache_insert, which eventually invokes _apc_cache_insert. Whether it's a user cache or a system cache, the overall execution is similar, as follows:   Position the current key in the slots array by the remainder operation: cache->slots[key.h% cache->num_slots]; After locating the position in the slots array, traverse the slot list of the current key, and clear the current slot if there is a slot key and a key match to write or slot expires. Insert the new slot after the last slot. Second, APC module installation under the installation of APC first step: Download Php_apc.dll in HTTP://PECL.PHP.NET/PACKAGE/APC to match the PHP version will php_apc.dll into your ext directory Step two: Let php.ini support the APC extension module. Then open php.ini add:   Code as follows: Extension=php_apc.dll apc.rfc1867 = on apc.max_file_size = 100M upload_max_filesize = 100M Pos T_max_size = 100M//above parameters can be defined by yourself   step three: Check to see if you support PHP APC apc_store apc_fetch Check phpinfo for APC dependencies   B.LIUNX Install APC first step: Download and install wget 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 install Step two: Configure APC in /usr/local/php/etc/php.ini Add the following configuration items:   Code as follows: Extension = "";; 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 three: check if the installation succeeded in restarting Apache or/usr/local/php/sbin/php-fpm restart see if there is an AP in the Phpinfo C Related item Three, configuration parameters detailed and use summary 1). The parameters of the APC module are detailed in the following code: apc.enabled   Boolean   apc.enabled can be set to 0来 disable APC. This is primarily useful when the APC is statically compiled into PHP because there is no other way to disable it (when compiling to DSO, you can comment out the extension line in the php.ini).   apc.shm_segments   INT   Allocate the number of shared memory blocks to the compilation cache. If the APC runs out of shared memory, and you have set the apc.shm_size to the maximum allowed by the system, you can try to increase the value of this parameter.   Apc.shm_size   Integral   the size of each shared memory block is in megabytes. By default, some systems (including most BSD variant systems) have a low size limit for shared memory blocks.   apc.optimization   integer optimization level. Set to 0 disables optimization, and the higher the value, the stronger the optimization. Look forward to a modest improvement in speed. This is still experimental in nature.   apc.num_files_hint   int prompts for the number of different source files that are included and requested on your Web server. If you are unsure, set to 0 or omit;A site that can be used primarily for thousands of source files.   APC.TTL   INT when a cache entry is required by another entry in the buffer, we need to consider the number of seconds that the cache entry is allowed to be idle in the buffer location. Setting this parameter to 0 means that your cache may be full of stale entries and that new entries cannot be cached.   The number of seconds that the Apc.gc_ttl   integer cache entry survives in the garbage collection list. This value provides an error protection in the event that a cache source file is executed while the server process is dead. If the source file is modified, the memory allocated to the old version of the cache entry will not be recycled until the TTL value is set to this parameter. Setting to 0 prohibits this feature. The   Apc.cache_by_default   Boolean defaults to on, but can be set to off and used in conjunction with apc.filters that begin with a plus sign, and the file is cached only when the filter is matched.   Apc.filters   String A comma-separated list of POSIX-extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note the filename used to match is the file name passed to Include/require, not 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, and if the first character is-then no match will be cached. -Is the default value, so it can be omitted.   Apc.mmap_file_mask   String (This paragraph is not quite understood, so there is no translation) If compiled with mmap support by using--enable-mmap this is the Mkte Mp-style file_mask to "mmap module for determing Whether your mmap ' Ed memory region ' 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 can also set it To/dev/zero to use your kernel ' S/dev/zero interface to Anonymous ' Ed Mmap. Leaving it undefined will force a anonymous mmap.    apc.slam_defense   int on a very busy server, whether you start the service or modify the file, you can cause a Multiple processes are trying to cache the same file competition at the same time. This option sets the percentage of the process skipping attempts to cache a file that is not cached. Or you can think of this as a chance for a separate process to skip caching. 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 it can reduce the collision probability of the cache. This attribute is disabled when set to 0.   Apc.file_update_protection   Integral when you modify a file on a running server, you should perform an atomic operation. That is, write a temporary file first, and then rename (MV) the file to its final position when it is finished. Many text editors, Cp,tar, and other similar programs do not operate this way. This means that there is a chance to access and (cache) the file when the file is still being written. The Apc.file_update_protection setting causes the cache to mark the delay of the new file. The default value is 2, which means that if the file is found to be modified for less than 2 seconds, the file will not be cached. Unfortunate users who visit half of the files will see bizarre situations, but at least this is not sustainable. If you are sure that you often use atomic operations to update your files, you can turn off this protection by setting this parameter to 0. If your system is full of IO operations and causes the update to take more than 2 seconds, you may need to increase the value. The   APC.ENABLE-CLI   integral type is mostly for testing and debugging. Start the APC feature for CLI version of PHP. In general, you will not think of creating, porting, and discarding the APC cache for each CLI request, but for a variety of test scenarios it is easy to turn on the APC for the CLI version.   2). Using summary 1, the spinlocks lock mechanism is used to achieve optimal performance. The 2,APC provides apc.php for monitoring and managing the APC cache. Don't forget to change the admin name and password 3,APC defaults to create shared memory by Mmap Anonymous mappings, which are stored in this "large" memory space. With the APC managing the shared memory 4, we need to adjust the values of apc.shm_size, apc.num_files_hints, and apc.user_entries_hint by statistics. Until the best 5, okay, I admit Apc.stat = 0 can achieve better performance. Anything I can do is acceptable. 6,php predefined constants, you can use the apc_define_constants () function. However, according to the APC developers said PECL HiDef performance better, throw a different define it, it is inefficient. 7, Function Apc_store (), for the system settings such as PHP variables, the lifecycle is the entire application (from the httpd daemon until the httpd daemon shutdown), the use of APC than memcached will be better. Must not go through the Network Transport Protocol TCP. 8,APC is not suitable for user data that is frequently changed through function Apc_store () caching, there are some strange phenomena.   IV. Use instances the APC cache class   code referenced below initphp framework is as follows: <?php  if  class apc{       /**   &N Bsp  * APC Cache-Settings Cache      * settings cache Key,value and cache time      * @param  string $key   key value &NB Sp    * @param  string $value value      * @param  string $time   Cache time     &NBSP ;*/      Public Function Set_cache ($key, $value, $time = 0) {         -if ($time = = 0) $time = null; Null case Permanent cache           return Apc_store ($key, $value, $time);;      }             /**      * APC Cache-Get cache      * cache data via key      * @param  string $key   key value      */      Public Function Get_cache ($key) {          return Apc_fetch ($key);     }  &N Bsp    /**      * APC Cache-Clear a cache      * remove a cache from Memcache      * @param & Nbsp;string $key   Key value      */      Public Function Clear ($key) {          return Apc_delete ($key);     }       /**      * APC Cache-Empty All caches      * do not recommend using this feature      * @return      */      public functi On Clear_all () {          apc_clear_cache (' user ');//clear User cache           RET Urn Apc_cleaR_cache (); Clear Cache      }       /**      * Check if APC cache exists      * @param  string $key   Key value      */      Public function exists ($key) {    &nbs P     return apc_exists ($key);     }       /**      * field self-used to remember Number      * @param string $key  key value      * @param int     $STEP new Step value      */      Public Function Inc. ($key, $step) {          return Apc_inc ($k EY, (int) $step);     }       /**      * field self-minus-for count     &NBSP ; * @param string $key  key value      * @param int     $STEP New step value      */      Public Function Dec ($key, $step) {          return Apc_dec ($key, (int) $step); &nbs P   }       /**      * return APC cache information      */      Public function info () {          return Apc_cache_info ();     } }
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.