PHP APC Cache configuration, Usage _php tutorial

Source: Internet
Author: User
Tags apc apc configuration apc module key string
I. Introduction to APC Cache
APC, the full name is alternative PHP cache, the 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 Cache
It means that APC caches the compiled results of the PHP file's source code and then compares the time stamp with each call. If it does not expire, it is run with the cached intermediate code. Default cache
3600s (one hour). However, this can still waste 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 will need to restart the Web server after changing the PHP code. This type of cache is currently used more often.
User Data caching
Caching is read and written by the user using the Apc_store and Apc_fetch functions when writing PHP code. If you have a small amount of data, you can try it. If the amount of data is large, it would be better to use a more monograph memory caching scheme similar to memcache this class
Cache key Generation rules
Each slot in the APC cache will have a key,key that is
apc_cache_key_t struct type, in addition to key-related properties, the key is the generation of the H field. The H field determines which position of this element falls in the slots array. There are different generation rules for the user cache and the system cache. The user cache generates a key through the Apc_cache_make_user_key function. Using the key string passed in by the user, depending on the hash function in the PHP kernel (the hash function used by PHP's Hashtable: Zend_inline_hash_func), the H value is generated.
The system cache generates a key through the Apc_cache_make_file_key function. Different scenarios are differentiated by the switch of the APC configuration item Apc.stat. In the case of open, that is,
Apc.stat= on, the compiled content is automatically recompiled and cached if it is updated. The H value at this point is the added value of the file's device and Inode. In the case of Apc.stat=off, when the file is modified, you must restart the Web server if you want the updated content to take effect. At this point the H value is generated based on the path address of the file, and the path here is the absolute path. Even if you are using a relative path, you will find the PG (include_path) location file to obtain an absolute path, so using an absolute path skips the check and can improve the efficiency of your code.
Adding a cache procedure
In the case of user caches, the Apc_add function is used to add content to the APC cache. If the key parameter is in a string, APC generates a key based on this string, and if the key parameter is an array, the APC traverses the entire array, generating the key. Based on these key,apc, the _apc_store is called to store the values 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, whose final call Apc_cache_user_insert performs a traversal query and write operation. In response, the system cache uses Apc_cache_insert to perform write operations, which eventually call _apc_cache_insert.
Whether the user cache or the system cache, the general process is similar, the steps are as follows:

Position the current key in the slots array by finding the remainder operation: cache->slots[key.h% cache->num_slots];
After locating the position in the slots array, iterate through the slot list of the current key, clearing the current slot if there is a key in the slot and a key match to write or the slot expires.
Insert a new slot after the last slot.
Second, APC module installation

Installing APC under
First step: Download Php_apc.dll in HTTP://PECL.PHP.NET/PACKAGE/APC to correspond with PHP version Php_apc.dll into your ext directory
Step two: Let PHP.ini support the APC expansion module. Then open php.ini join:
Copy the Code code 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 themselves

Step three: Check if PHP APC apc_store Apc_fetch is supported
See if there are APC related items in the Phpinfo

installing APC under B.liunx
First step: Download and install
TAR-ZXVF apc-3.1.8.tgz CD APC-3.1.8
./configure--ENABLE-APC--enable-mmap--enable-apc-spinlocks--disable-apc-pthreadmutex--with-php-config=/usr/ Local/php/bin/php-config
sudo make install
Step Two: Configure APC
Add the following configuration entries in/usr/local/php/etc/php.ini:
Copy CodeThe code is 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 was successful
Restart Apache or/usr/local/php/sbin/php-fpm restart
See if there are APC related items in the Phpinfo
iii. configuration parameters and Usage summary
1). Detailed parameter configuration for APC modules

Copy CodeThe code is as follows:
apc.enabled Boolean type
Apc.enabled can be set to a% to disable APC. This is mostly 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 Integral type
The number of shared memory blocks allocated to the compilation cache. If the APC is running out of shared memory and you have set Apc.shm_size to the maximum allowable value for the system, you can try to increase the value of this parameter.

Apc.shm_size Integral type
The size of each shared memory block is in megabytes. By default, the size of shared memory blocks for some systems (including most BSD variant systems) is very low.

Apc.optimization Integral type
Optimization level. Set to 0 to disable optimization, the higher the value the more powerful the optimization is used. Expect to have moderate speed improvements. This is still an experimental nature.

Apc.num_files_hint Integral type
A hint to 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 primarily for sites that have thousands of source files.

Apc.ttl Integral type
When a cache entry is required by another entry in the buffer location, 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 filled with stale entries and that new entries cannot be cached.

Apc.gc_ttl Integral type
The number of seconds that the 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 set by this parameter is reached. Setting to 0 disables this feature.

Apc.cache_by_default Boolean type
The default is on, but can be set to off and used with the apc.filters with the plus sign, and the file is cached only when matching the filter.

Apc.filters string
A comma-delimited list of POSIX extended regular expressions. If any pattern matches the source file name, 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 +, then 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 really does not understand, 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 DET Erming whether your mmap ' Ed memory region was 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). 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 would force an anonymous mmap.

Apc.slam_defense Integral type
On a very busy server, whether you start the service or modify the file, you will cause a multi-process to try to cache the same file 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 single process that skips the cache's chances. 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 it will be to reduce the probability of collisions with the cache. Set to 0 to disable this feature.

Apc.file_update_protection Integral type
When you modify a file on a running server, you should perform atomic operations. That is, write a temporary file, and then rename (MV) the file to its final location when you finish writing it. Many text editors, Cp,tar, and other similar programs do not. This means there is a chance to access and (cache) the file when the file is still being written. The Apc.file_update_protection setting allows the cache to mark the delay of a new file. The default value is 2, which means that files will not be cached if they are found to be less than 2 seconds away from the time the file was modified. The unfortunate user who accesses half of the files will see the bizarre situation, but at least this is not a continuous situation. If you are sure that you often use atomic operations to update your files, you can turn this protection off by setting this parameter to 0. If your system is full of IO operations and causes the updater to take more than 2 seconds, you may need to increase this value.

Apc.enable-cli Integral type
Mostly for testing and debugging. Start the APC function for CLI version PHP. In general, you will not expect to create, port, and discard APC caches for each CLI request, but for various test scenarios it is easy to open APC for the CLI version.

2). Usage Summary
1, using spinlocks lock mechanism, can achieve the best performance.
The 2,APC provides apc.php for monitoring and managing the APC cache. Don't forget to change your administrator name and password
3,APC By default, the shared memory is created by Mmap Anonymous mappings, and the cache objects are stored in this "large" memory space. The shared memory is managed by APC itself
4, we need to adjust the value of Apc.shm_size, Apc.num_files_hints, apc.user_entries_hint by statistics. Until the best
5, okay, I admit that Apc.stat = 0 can achieve better performance. Anything I can do is acceptable.
6,php pre-defined constants, you can use the apc_define_constants () function. However, according to APC developers said PECL HiDef better performance, define it, it is inefficient.
7, Function Apc_store (), for PHP variables such as system settings, the lifecycle is the entire application (from the httpd daemon until the httpd daemon shuts down), using APC is better than memcached. Must not go through the Network Transport Protocol TCP.
8,APC is not suitable for caching frequently changed user data through the function Apc_store (), there are some strange phenomena.

Iv. Examples of Use
The following is a reference to the APC cache class for the initphp framework
Copy CodeThe code is as follows:
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; Null in the case of a permanent cache
Return Apc_store ($key, $value, $time);;

* APC Cache-Get Cache
* Get cached data from key
* @param string $key key value
Public Function Get_cache ($key) {
Return Apc_fetch ($key);

* APC Cache-Clears a cache
* Delete a cache from Memcache
* @param string $key key value
Public function Clear ($key) {
Return Apc_delete ($key);

* APC Cache-Clears all caches
* It is not recommended to use this feature
* @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 self-increment-for counting
* @param string $key key value
* @param int $step New Step value
Public Function Inc ($key, $step) {
Return Apc_inc ($key, (int) $step);

* Field auto minus-for counting
* @param string $key key value
* @param int $step 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 ();
} true techarticle First, APC cache introduction APC, the full name is alternative PHP cache, the official translation is called "Optional PHP cache." It provides us with a framework for caching and optimizing PHP's intermediate code. APC Cache points ...

  • 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.

    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.