PHP cache configuration APC cache configuration

  • 2021-01-25 07:17:47
  • OfStack

1. An introduction to APC caching
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's intermediate code. The APC cache has two parts: the system cache and the user data cache.
System cache
It means that APC caches the compiled PHP source code, and then compares the time mark on each call. If it is not expired, it is run using cached intermediate code. The default cache
3600s(1 hour). But this still wastes a lot of CPU time. It is therefore possible to set the system cache to never expire in php.ini (apc.ttl=0). However, if this is the case, the WEB server will need to be restarted after the php code is shipped. This type of cache is used more often today.
User data cache
The cache is read and written by the user when writing PHP code using apc_store and apc_fetch functions. If the amount of data is not large, you can try 1. If the data volume is large, it is better to use a more specialized memory caching scheme such as memcache
Cache key generation rules
Each slot in the APC cache will have one key, key is
apc_cache_key_t structure type. In addition to key related attributes, the key is the generation of h fields. The h field determines where the element falls in the slots array. The generation rules are different for user caches and system caches. The user cache generates key through the apc_cache_make_user_key function. The h value is generated by the key string passed in by the user, relying on the hash function in the PHP kernel (hash function used by hashtable: zend_inline_hash_func).
The system cache generates key through the apc_cache_make_file_key function. APC configuration item apc.stat switch to treat different solutions. In the case of on, i.e
apc. stat= On, automatically recompile and cache the compiled content if updated. The value of h at this point is the sum of device and inode of the file. In the case of shutdown, apc.stat =off, the Web server must be restarted if the updated content is to take effect after the file has been modified. At this point, the ES86en value is generated according to the path address of the file, and the path here is the absolute path. Even if you are using relative paths, you will look for the PG(include_path) location file to get the absolute path, so using absolute paths bypasses checks and improves code efficiency.
Adding a cache procedure
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 will generate key from the string. If the key parameter is an array, APC will traverse the array and generate key. Based on these key, APC calls _apc_store to store the value in the cache. Since this is a user cache, the cache in use is currently apc_user_cache. The write operation is performed by the function apc_cache_make_user_entry, which finally calls apc_cache_user_insert to perform the traversal query and write operation. Correspondently, the system cache uses apc_cache_insert for write operations, which eventually call _apc_cache_insert.
For both user cache and system cache, the general implementation process is similar. The steps are as follows:

To locate the current key position in the slots array: cache- > slots[key.h % cache- > num_slots];
After locating the position in the slots array, traverse the linked list of slot corresponding to the current key. If there is a match between key and the written key or slot is expired, clear the current slot.
Insert a new slot after the last slot.
2. APC module installation

A. Install APC under WINDOWS
Step 1: download php_apc dll http: / / pecl php. net package/apc with php version will php_apc. The corresponding dll into your ext directory
Step 2: Make php.ini support the apc extension module. Then open php.ini to add:

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 for apc related entries in phpinfo

B. Install APC under 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
In/usr local/php/etc/php ini to join the following configuration items:


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 that the installation was successful
Restart apache or/usr/local/php/sbin/php - fpm restart
Check for apc related entries in phpinfo
3. Detailed explanation of configuration parameters and summary of use
1). Detailed description of APC module parameter configuration

 
apc.enabled   The Boolean  
apc.enabled  It can be set to zero  0  To disable  APC . This is mainly useful when  APC  Statically compiled into  PHP  Because there is no other way to disable it (when compiled to  DSO  When, can be  php.ini  In the  extension  Line comment out). 

apc.shm_segments   The integer  
 The number of shared memory blocks allocated to the compile cache. if APC Out of shared memory, and you've set it apc.shm_size You can try to increase the value of this parameter to the maximum allowed by the system. 

apc.shm_size   The integer  
 The size of each shared memory block is MB Is in units. By default, 1 Some systems (including most BSD Variant system) has a very low limit on the size of the shared memory block. 

apc.optimization   The integer 
 Optimization level. Set to 0 Optimization is disabled, and the higher the value, the more powerful the optimization. Expect a modest speed improvement. This is still experimental. 

apc.num_files_hint   The integer 
 For in you Web Indicates the number of different source files on the server that are contained and requested. If you are not sure, set to 0 Or omit; This setting is likely to be used primarily for sites with thousands of source files. 

apc.ttl   The integer 
 when 1 The location of the cache entries in the cache is separate 1 When the number of entries is needed, we need to consider the number of seconds that the cache entry is allowed to be idle in the cache. Set this parameter to 0 This means that your cache may be full of stale items, and new items may not be cached. 

apc.gc_ttl   The integer 
 The number of seconds that a cache entry lives in the garbage collection list. This value provides error protection during execution 1 Cache source files while the server process dies at the same time. If the source file is modified, cache entries allocated to older versions will not be reclaimed until this parameter is set TTL When it's worth it. Set to 0 Just disable this feature. 

apc.cache_by_default   The Boolean 
 The default is On But can be set to Off And that starts with a plus sign apc.filters Used in conjunction, files are cached only if they match the filter. 

apc.filters   string 
1 Is separated by a comma POSIX Expand the list of regular expressions. If any pattern matches the source file name, the file will not be cached. Note that the filename used to match is passed to  include/require  File name instead of the absolute path. If the first of the regular expressions 1 A character is  +  , this expression means that any file matching the expression will be cached if the 1 A character is  -  Any matches will not be cached.  -  Is the default value, so it can be omitted. 

apc.mmap_file_mask   string   (This paragraph is really not very understand, so 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. 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   The integer 
 On a very busy server, whether you start a service or modify a file, you will cause 1 Various processes are trying to work together 1 The same time cache 1 The file competition. This option sets the process to skip attempts to cache 1 The percentage of files that are not cached. Or you can think of this as 1 The probability that a single process will skip the cache. For example, setting apc.slam_defense for 75 That means the process has 75% The probability of not caching uncached files. Therefore, the higher the setting, the more likely it is to reduce the chance of cache collisions. Set to 0 This feature is disabled. 

apc.file_update_protection   The integer 
 When you are in 1 When modifying files on a running server, you should perform atomic operations. So let's just write it 1 Temporary file, rename it when it is finished ( mv This file goes to its final location. Many text editors, cp . tar And other 1 These programs don't work that way. This means there is an opportunity to access and cache files while they are still being written. apc.file_update_protection The Settings of the The default value is 2 Means that if a file is found to have been modified less than the access time 2 Seconds, the file will not be cached. Access to write 1 Half the unfortunate users of the file will see bizarre situations, but at least the situation will not last. 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 Operation and cause the update program to cost more than 2 In seconds, you might want to increase it. 

apc.enable-cli   The integer 
 Mostly for testing and debugging. for CLI Version of the PHP Open start APC Function. 1 Generally speaking, you will not think about it for every 1 a CLI Request creation, migration, and abandonment APC The cache, but for a variety of testing situations, this is easy for the sake of CLI Version of the open APC . 

2). Use summary
1. The Spinlocks locking mechanism can achieve the best performance.
2,APC provides apc.php is used to monitor and manage the APC cache. Don't forget to change the administrator name and password
3. By default,APC creates shared memory via mmap anonymous mapping, and cache objects are stored in this "large" memory space. APC manages this shared memory itself
4. We need to adjust the values of apc.shm_size, apc.num_files_hints, apc.user_entries_hint by statistics. Until the best
5. Well, I admit that apc.stat = 0 gives better performance. I can do anything.
6,PHP predefined constants, you can use the apc_define_constants() function. However, according to the developers of the APC, the hidef is more efficient and inefficient than the define.
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 shuts down), it is better to use APC than Memcached. Do not go through the network transmission protocol tcp.
8,APC is not suitable for caching user data with frequent changes through the function apc_store(). Some strange phenomena may occur.

4. Use instances
The following reference is to the APC cache class of the initphp framework


<?php 
if 
class Apc{ 

    /**
     * Apc The cache - Set the cache 
     *  Set the 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 Permanent cache in case  
        return apc_store($key, $value, $time);; 
    } 

     
    /**
     * Apc The cache - Access to the cache 
     *  through KEY Get cached data 
     * @param  string $key   KEY value 
     */ 
    public function get_cache($key) { 
        return apc_fetch($key); 
    } 

    /**
     * Apc The cache - remove 1 A cache 
     *  from memcache Remove the 1 The cache 
     * @param  string $key   KEY value 
     */ 
    public function clear($key) { 
        return apc_delete($key); 
    } 

    /**
     * Apc The cache - Clear all caches 
     *  This feature is not recommended 
     * @return
     */ 
    public function clear_all() { 
        apc_clear_cache('user'); // Clear the user cache  
        return apc_clear_cache(); // Clear the cache  
    } 

    /**
     *  check APC Whether the cache exists or not 
     * @param  string $key   KEY value 
     */ 
    public function exists($key) { 
        return apc_exists($key); 
    } 

    /**
     *  Fields on the - Is used to count 
     * @param string $key  KEY value 
     * @param int    $step  The addition of step value 
     */ 
    public function inc($key, $step) { 
        return apc_inc($key, (int) $step); 
    } 

    /**
     *  Fields since the reduction - Is used to count 
     * @param string $key  KEY value 
     * @param int    $step  The addition of step value 
     */ 
    public function dec($key, $step) { 
        return apc_dec($key, (int) $step); 
    } 

    /**
     *  return APC Cache information 
     */ 
    public function info() { 
        return apc_cache_info(); 
    } 
}


Related articles: