Detailed introduction of PHP's APC cache

Introduction of APC

The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. Its goal is to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.

APC official website: http://www.php.net/manual/en/book.apc.php

Download address of the latest version under WIN: http://downloads.php.net/pierre/   

Download link: http://downloads.php.net/pierre/php_apc-3.1.4-5.3-VC6-x86.zip   Use the corresponding DLL according to your own PHP compiled version

1. Introduction to APC Cache

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's cache is divided into two parts: system cache and user data cache.

system cache

It means that APC caches the compilation result of PHP file source code, and then compares the time stamp every time it is called. If not expired, run using the cached veneer. The default cache is 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 like this, you need to restart the WEB server after changing the php code. Currently used more refers to this type of cache.

Reference knowledge points:

APC can remove the time of php dynamic parsing and compilation, and php scripts can be executed faster. The picture below is a good illustration of why apc can make php scripts run faster.

PHP is a dynamic scripting language, so in order for users to see the content of the page in the browser, the server must parse the php code to generate the desired html code. As can be seen from the above figure, when there is no apc, the server needs to parse, compile and execute php every time the user requests a php page, but in many cases, as long as the php code does not change, the php The execution logic will not change, that is to say, the process of parsing and compiling can be omitted, just execute it directly and return the result. This is the job of apc. Apc caches the executable code of php, thus eliminating the process of parsing and compiling, and speeding up the execution of php scripts.

 

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 try it. If the amount of data is large, it would be better to use a more dedicated memory cache solution like memcache

Reference knowledge point:
In addition to caching php code, apc can also cache user data, but because apc has a small capacity, it is best to cache data that has not changed for a long time, and the constant unit should be in Celestial unit. So if the data changes frequently and the amount of data is relatively large, then don't use apc, you can use memcache or Redis .

Cache key generation rules

Each slot in the APC cache will have a key. The key is of the apc_cache_key_t structure type. Except for 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 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 a key through the apc_cache_make_file_key function. Different schemes are treated differently through the switch of the APC configuration item apc.stat. In the case of opening, that is, when apc.stat= On, if it is updated, it will automatically recompile and cache the compiled content. The h value at this time is the value obtained by adding the device and inode of the file. In the case of closing, that is, when 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 according to 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 an absolute path, so using an absolute path will skip the check and improve code efficiency.

Common APC Settings

apc.cache_by_default Caching is enabled by default. 1 means "enabled", 0 means "disabled"
apc.filters Determine whether a file needs to be cached or not based on comma-separated POSIX regular expressions. A regular
expression starting with a+ will force APC not to cache any files matching this regular expression. A regular expression starting with a- will force
APC to cache any file matching this regular expression
apc.stat Enables or disables APC's checking of all requested PHP scripts for changes. This process is performed each time the script is invoked
. If you disable this setting, you will need to restart the web server after making any changes to the PHP script to
clear the cache and change the script content. 0=disable, 1=enable, default 1
apc.enabled Enable or disable APC caching. 0=disable, 1=enable, default 1
apc.shm_size Set the shared memory size that APC allows to use, this value is in megabytes
apc.shm_segments Sets the total number of shared memory segments available
apc.include_once_override Enable or disable optimizations for include_once and require_once. When this setting is enabled, extra system calls made by PHP intrinsics are reduced. 0=disable, 1=enable, default 0
apc.optimization Set optimization level. 0=Disable optimization function
apc.num_files_hint Set the number of files you think should be cached. The default value is 1000, if you are not sure about the number of files, you can set 0
apc.ttl Sets the expiration time for files stored in the cache, in seconds.
apc.write_lock Enabling this setting will force individual processes to cache certain scripts. Suitable for high-traffic web servers or applications that must cache multiple files

 An example configuration is as follows: 

extension= apc.so   
apc.enabled=1  
apc.shm_segments=1   
apc.shm_size=64M ; apc内存的大小,最后的大小需要乘上segments的数量,所以这里一共为apc分配64M   
apc.ttl=7200   
apc.user_ttl=7200  
apc.enable_cli=1 ; 这个如果不开启,则只可以在网页上进行apc操作,不能通过cli进行apc操作  

Add 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 a string, APC will generate a key based on the string. If the key parameter is an array, APC will traverse the entire array to generate a key. According to 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. It is the apc_cache_make_user_entry function that performs the write operation, which finally calls apc_cache_user_insert to perform traversal query and write operations. Correspondingly, the system cache uses apc_cache_insert to perform write operations, which will eventually call _apc_cache_insert.

Regardless of whether it is user cache or system cache, the general execution process is similar, and the steps are as follows:

  1. Locate the position of the current key in the slots array through the remainder operation: cache->slots[key.h % cache->num_slots];
  2. 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, clear the current slot.
  3. Insert the new slot after the last slot.

2. APC module installation

WINDOWS

Step 1: Download php_apc.dll at http://pecl.php.net/package/apc To match the php version, put php_apc.dll into your ext directory

The second step: Let php.ini support the apc extension module. Then open php.ini and add:

extension=php_apc.dll
apc.rfc1867 = on
apc.max_file_size = 100M
upload_max_filesize = 100M
post_max_size = 100M

//以上参数可自己定义

Step 3: Check whether it supports PHP APC apc_store apc_fetch PHP APC configuration parameters explain related configurations together.

apc.enabled=1 The default value of apc.enabled is 1, you can set it to 0 to disable APC. If you set it to 0, also comment out extension=apc.so (this can save memory resources). Once the APC function is enabled, Opcodes will be cached in shared memory.

apc.shm_segments = 1

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 best

5, Well, I admit that apc.stat = 0 can get better performance. I can accept anything you want me to do.

6, PHP predefined constants, you can use the apc_define_constants () function. However, according to APC developers, pecl hidef has better performance, let’s throw away define, it is inefficient.

7. The function apc_store(), for PHP variables such as system settings, the life cycle is the entire application (from the httpd daemon process until the httpd daemon process is closed), it is better to use APC than Memcached. After all, do not go through the network transmission protocol tcp.

8. APC is not suitable for caching user data that changes frequently through the function apc_store(), and some strange phenomena will occur.

LIUNX

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

Add in /usr/local/php/etc/php.ini

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

Restart apache or /usr/local/php/sbin/php-fpm restart

View phpinfo apc

The following references the APC cache class of the www.initphp.com framework

APC cache class of initphp framework

<?php  
if (!defined('IS_INITPHP')) exit('Access Denied!');  
/********************************************************************************* 
 * InitPHP 2.0 国产PHP开发框架  Dao-APC缓存 不适合频繁写入的缓存数据 
 *------------------------------------------------------------------------------- 
 * 版权所有: CopyRight By initphp.com 
 * 您可以自由使用该源码,但是在使用过程中,请保留作者信息。尊重他人劳动成果就是尊重自己 
 *------------------------------------------------------------------------------- 
 * $Author:zhuli 
 * $Dtime:2011-10-09  
***********************************************************************************/  
class apcInit {  
      
    /** 
     * Apc缓存-设置缓存 
     * 设置缓存key,value和缓存时间 
     * @param  string $key   KEY值 
     * @param  string $value 值 
     * @param  string $time  缓存时间 
     */  
    public function set_cache($key, $value, $time = 0) {   
        if ($time == 0) $time = null; //null情况下永久缓存  
        return apc_store($key, $value, $time);;  
    }  
      
      
    /** 
     * Apc缓存-获取缓存 
     * 通过KEY获取缓存数据 
     * @param  string $key   KEY值 
     */  
    public function get_cache($key) {  
        return apc_fetch($key);  
    }  
      
    /** 
     * Apc缓存-清除一个缓存 
     * 从memcache中删除一条缓存 
     * @param  string $key   KEY值 
     */  
    public function clear($key) {  
        return apc_delete($key);  
    }  
      
    /** 
     * Apc缓存-清空所有缓存 
     * 不建议使用该功能 
     * @return 
     */  
    public function clear_all() {  
        apc_clear_cache('user'); //清除用户缓存  
        return apc_clear_cache(); //清楚缓存  
    }  
      
    /** 
     * 检查APC缓存是否存在 
     * @param  string $key   KEY值 
     */  
    public function exists($key) {  
        return apc_exists($key);  
    }  
      
    /** 
     * 字段自增-用于记数 
     * @param string $key  KEY值 
     * @param int    $step 新增的step值 
     */  
    public function inc($key, $step) {  
        return apc_inc($key, (int) $step);  
    }  
      
    /** 
     * 字段自减-用于记数 
     * @param string $key  KEY值 
     * @param int    $step 新增的step值 
     */  
    public function dec($key, $step) {  
        return apc_dec($key, (int) $step);  
    }  
      
    /** 
     * 返回APC缓存信息 
     */  
    public function info() {  
        return apc_cache_info();  
    }  
} 

PHP apc cache and comparison with redis

Guess you like

Origin blog.csdn.net/qq_31432773/article/details/128342487