Home Backend Development PHP Tutorial Detailed introduction to PHP's APC cache (learning and organization)_PHP tutorial

Detailed introduction to PHP's APC cache (learning and organization)_PHP tutorial

Jul 13, 2016 pm 05:54 PM
apc ca php introduce study tidy yes Introduction cache detailed

1. Introduction to APC cache
APC, the full name is Alternative PHP Cache, and 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 results of the PHP file source code, and then compares the time stamps every time it is called. If not expired, the cached intermediate code is used to run. Default cache
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 up like this, you need to restart the WEB server after changing the PHP code. Currently, this type of cache is commonly used.
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 give it a try. If the amount of data is large, it would be better to use a more specialized memory caching solution like memcache
Cache key generation rules
Each slot in the APC cache will have a key, and the key is
The apc_cache_key_t structure type, in addition to the key-related attributes, the key is the generation of the h field. The h field determines where in the slots array this element falls. The generation rules are different for user cache and system cache. The user cache generates keys 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 keys through the apc_cache_make_file_key function. Different solutions can be treated differently through the switch of the APC configuration item apc.stat. In the case of open, i.e.
When apc.stat= On, the compiled content will be automatically recompiled and cached if updated. The h value at this time is the value obtained by adding the device and inode of the file. In the case of shutdown, that is, when apc.stat=off, when the file is modified, if you want the updated content to take effect, you must restart the web server. 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 use a relative path, the PG (include_path) location file will be searched to obtain the absolute path, so using an absolute path will skip the check and improve the efficiency of the code.
Add caching 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 the key based on the string. If the key parameter is an array, APC will traverse the entire array and generate the key. Based on these keys, APC will call _apc_store to store the value in the cache. Since this is a user cache, the cache currently used is apc_user_cache. It is the apc_cache_make_user_entry function that performs the write operation, which ultimately calls apc_cache_user_insert to perform the traversal query and write operation. Correspondingly, the system cache uses apc_cache_insert to perform write operations, which will eventually call _apc_cache_insert.
Whether it is user cache or system cache, the general execution process is similar. The steps are as follows:

Locate the position of the current key in the slots array through the remainder operation: 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 there is a slot key that matches the key to be written or the slot expires, clear the current slot.
Insert a 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

Step 2: 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

//The above parameters can be defined by yourself

Step 3: Check whether PHP APC is supported apc_store apc_fetch PHP APC configuration parameters Explain the 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. Using the 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. 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, OK, I admit that apc.stat = 0 can get better performance. I can accept whatever you want.

6, PHP predefined constants, you can use the apc_define_constants() function. However, according to APC developers, pecl hidef has better performance. Just throw out define, which 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). It is better to use APC than Memcached. After all, do not use the network transmission protocol tcp.

8. APC is not suitable for caching frequently changed user data 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 domestic PHP development framework Dao-APC cache is not suitable for frequently written cache data
*------------------------------------------------ ----------------------------------
* Copyright: CopyRight By initphp.com
* You can use this source code freely, but please keep the author information during use. Respecting the fruits of others’ labor means respecting yourself
*------------------------------------------------ ----------------------------------
* $Author:zhuli
* $Dtime:2011-10-09
*************************************************** **********************************/
class apcInit {
       
/**
* 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 in case of null
          return apc_store($key, $value, $time);;
}  
       
       
/**
* Apc cache-get cache
* Get cache data through 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
* It is 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 New 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 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();
}  
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477944.htmlTechArticle1. Introduction to APC Cache APC, the full name is Alternative PHP Cache, and the official translation is called Alternative PHP Cache. It provides us with a framework for caching and optimizing PHP's intermediate code. APC's cache is divided into two parts...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles