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 details the introduction of PHP APC module, parameter configuration, installation steps, and use examples. Since part of the content is translated from the PHP Manual, there may be incompleteness. Hope to get your corrections
I. Introduction to APC cache
APC, the full name is Alternative PHP Cache, the official translation is "optional PHP cache". It provides us with a framework for caching and optimizing PHP intermediate code. APC's cache is divided into two parts: system cache and user data cache.
System cache
It means that APC caches the compilation results of the source code of the PHP file, and then compares the time stamps each time it is called. If it has not expired, it uses the cached intermediate code to run. Default cache
 3600s (one hour). But this will still waste a lot of CPU time. So you can set the system cache in php.ini to never expire (apc.ttl = 0). However, if this is set, you need to restart the WEB server after changing the php code. Currently used more refers to this type of cache.
User data cache
The cache is read and written by users using apc_store and apc_fetch functions when writing PHP code. If the amount of data is not large, you can try it. If the amount of data is large, it would be better to use a more monolithic memory cache scheme like memcache
Cache key generation rules
Each slot in the APC cache will have a key, the key is
 The apc_cache_key_t structure type, in addition to key-related attributes, the key is the generation of the h field. The h field determines where this element falls in the slots array. For user cache and system cache, the generation rules are different. The user cache generates a key through the apc_cache_make_user_key function. The key string passed in 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 generates a key through the apc_cache_make_file_key function. Different schemes are treated differently through the switch of APC configuration item apc.stat. In the open situation, ie
 When apc.stat = On, it will automatically recompile and cache the compiled content if it is updated. The value of h at this time is the value obtained by adding the device and inode of the file. In the case of shutdown, that is, apc.stat = off, when the file is modified, if the updated content is to take effect, the Web server must be restarted. 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 are using a relative path, it will find the PG (include_path) location file to obtain the absolute path, so using the absolute path will skip the check and improve the efficiency of the code.
Adding a 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 in a string, APC will generate a key based on this string. If the key parameter is an array, APC will traverse the entire array to generate a key. Based on these keys, APC will call _apc_store to store the value in the cache. Since this is a user cache, the currently used cache is apc_user_cache. Performing the write operation is the apc_cache_make_user_entry function, which finally calls apc_cache_user_insert to perform traversal queries and write operations. Correspondingly, the system cache uses apc_cache_insert to perform write operations, and it will eventually call _apc_cache_insert.
Whether it is user cache or system cache, the general implementation process is similar, the steps are as follows:

Through the remainder operation, locate the position of the current key in the slots array: 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 slot key 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
The first step: download php_apc.dll at http://pecl.php.net/package/apc to correspond to the php version put php_apc.dll in your ext directory
Step 2: Let php.ini support the apc extension module. Then open php.ini and add:
Copy the code:
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 if PHP APC apc_store apc_fetch is supported
See if there are apc related items in phpinfo

B.LIUNX install APC
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:

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
See if there are apc related items in phpinfo
3. Detailed configuration parameters and use summary
1). APC module parameter configuration explained in detail

Copy the code:

apc.enabled Boolean
apc.enabled can be set to 0 to disable APC. This is mainly useful when 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 php.ini).

apc.shm_segments integer
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, the shared memory block size of some systems (including most BSD variant systems) is very low.

apc.optimization integer
Optimization level. Set to 0 to disable optimization. Higher values use more powerful optimizations. Expect modest speed improvements. This is experimental.

apc.num_files_hint integer
Prompt 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; this setting may be used mainly for sites with thousands of source files.

apc.ttl integer
When a cache entry is needed by another entry in the cache area, we need to consider 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 cannot be cached.

apc.gc_ttl Integer
The number of seconds that cache entries survive in the garbage collection list. This value provides error protection during the execution of a cached source file while the server process dies. If that source file is modified, the cache entries allocated to the old version of the memory will not be recovered until the TTL value set by this parameter is reached. Set to 0 to disable this feature.

apc.cache_by_default Boolean
The default is On, but can be set to Off and used in conjunction with apc.filters starting with a plus sign. The file is only cached when it matches 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 for matching is the file name passed to include / require, not the absolute path. If the first character of the regular expression is +, then this expression means that any file matching the expression will be cached, if the first character is-, then any match will not be cached. -It is the default value, so it can be omitted.

apc.mmap_file_mask string (this paragraph is not very understandable, 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 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 a .shm somewhere in your mask. eg /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 cause a race for multiple processes to try to cache the same file at the same time. This option sets the percentage of processes that skipped trying to cache an uncached file. Or you can think of this as the chance of a separate 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 less the chance of collision in the cache. Set to 0 to disable this feature.

apc.file_update_protection integer
When you modify files 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 after writing. Many text editors, cp, tar, and other similar programs do not do this. This means the opportunity to access and (cache) the file while the file is still being written. The setting of apc.file_update_protection makes the cache delay marking new files. The default value is 2, meaning 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. Unfortunate users who access half of the files written will see bizarre situations, but at least this situation is not persistent. 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 it takes more than 2 seconds to update the program, 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. In general, you will not think of creating, porting, and abandoning APC caches for every CLI request, but for various test cases, it is easy to enable APC for the CLI version.

2). Use summary
1, using Spinlocks lock mechanism, can 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. By default, APC creates shared memory through mmap anonymous mapping, and cache objects are stored in this "large" memory space. The shared memory is managed by APC
4. We need to adjust the values of apc.shm_size, apc.num_files_hints, and apc.user_entries_hint through statistics. Until the most good
5. Well, I admit that apc.stat = 0 can get better performance. Whatever I want is acceptable.
6, PHP pre-defined constants, you can use the apc_define_constants () function. However, according to APC developers, pecl hidef has better performance. Definitely, it 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). Using APC is better than Memcached. Must not go through the network transmission protocol tcp.
8, APC is not suitable for caching frequently changed user data through the function apc_store (), there will be some strange phenomena.

Fourth, the use case
The following references the APC cache class of the initphp framework
Copy the code:

<? php
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; // permanent cache if null
        return apc_store ($ key, $ value, $ time) ;;
    }

    
    / **
     * Apc cache-get cache
     * Get cached data via 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
     * Not recommended to use this function
     * @return
     * /
    public function clear_all () {
        apc_clear_cache ('user'); // Clear user cache
        return apc_clear_cache (); // clear cache
    }

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

    / **
     * Field increment-used for counting
     * @param string $ key KEY value
     * @param int $ step Added step value
     * /
    public function inc ($ key, $ step) {
        return apc_inc ($ key, (int) $ step);
    }

    / **
     * Field decrement-used for counting
     * @param string $ key KEY value
     * @param int $ step Added step value
     * /
    public function dec ($ key, $ step) {
        return apc_dec ($ key, (int) $ step);
    }
    
    / **
     * Returns APC cache information
     * /
    public function info () {
        return apc_cache_info ();
    }
}


Relevant information:
APC cache settings, use and installation
http://blog.csdn.net/liuxinmingcode/article/details/8058864


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.