PHP Opcache works

PHP projects, especially in the large flow of high concurrency scenarios, the PHP how to improve response time, is a very important job.

The Opcache is to optimize the performance of PHP component can not be missing, especially the application of a PHP framework of the project, the effect is even more evident.

1 Overview

Before understanding OPCache function, we need to first understand the mechanism of PHP-FPM + Nginx working mechanism, as well as the implementation of the PHP script interpreter.

1.1 PHP-FPM + Nginx working mechanism

Request from a Web browser to Nginx, PHP and then processing is complete, a total involves the following five steps:

The first step: Start Services

  • Start PHP-FPM. PHP-FPM supports two communication modes: TCP socket and Unix socket;

  • PHP-FPM will launch two types of processes: Master Worker process and the process, the former responsible for monitoring port, assign tasks, manage Worker process; the latter is a PHP-cgi program, responsible for interpreting compile and execute PHP scripts.

  • Start Nginx. First of all loads ngx_http_fastcgi_module module, FastCGI initialization execution environment, to achieve the FastCGI protocol Request Broker

  • Here we must note: fastcgi of worker process (cgi process), is managed by PHP-FPM, not Nginx. Nginx just proxy

Step two: Request => Nginx

  • Nginx receives the request, and the configuration based on location, select an appropriate handler

  • Here is the agent of PHP handler

The third step: Nginx => PHP-FPM

  • Nginx fastcgi request translated into the request

  • Send to master the process of PHP-FPM via TCP socket / Unix Socket

Step Four: PHP-FPM Master => Worker

  • PHP-FPM master process receives the request

  • Worker allocation process executes PHP script, if there is no idle Worker, return 502 error

  • Worker (php-cgi) PHP script execution process, if the timeout, return 504 error

  • Processing ends and returns results

Step five: PHP-FPM Worker => Master => Nginx

  • PHP-FPM Worker process returns processing results, and closes the connection, to wait for a next request

  • PHP-FPM Master process returns to the processing results through the Socket

  • Nginx Handler sequentially transmitted to each of the first buffer in response to a second filter → → → and so the final response sent to the client

1.2 PHP script to explain the mechanism of execution

PHP + Nginx understanding of the overall process flow, we next look at the specific PHP script execution process, first we look at an example:

<?php
if (!empty($_POST)) {
    echo "Response Body POST: ", json_encode($_POST), "\n";
}

if (!empty($_GET)) {
    echo "Response Body GET: ", json_encode($_GET), "\n";
}

We analyze the implementation process:

  1. php link initialization execution, start Zend engine load registered extension modules

  2. After reading the initialization script, Zend engine script file lexical analysis (lex), parsing (bison), generative grammar tree

  3. Zend Engine compiled syntax tree, generated opcode,

  4. Zend engine executes opcode, return the results

In PHP cli mode, each execution of PHP scripts, four steps are sequentially performed again;

In PHP-FPM mode, Step 1) is performed if start a PHP-FPM, subsequent requests not executed; Step 2) to 4) every request executed again;

In fact, Step 2), 3) the resulting syntax tree and opcode, the same result every time you run a PHP script is the same,

In PHP-FPM mode, each request must be processed again, is a great waste of system resources, then there is no way to optimize it?

Of course, such as:

  • OPCache: formerly known as Zend Optimizer +, is an open source component of Zend Server; official produced, highly recommended

  • APC: Alternative PHP Cache is an open and free PHP opcode cache components for caching, optimizing PHP intermediate code; has not updated is not recommended

  • APCu: is a branch of the APC, shared memory, user data cache, the cache of opcode can not, be used with Opcache

  • eAccelerate: the same is not updated, and is not recommended

  • xCache: no longer recommended for use

2. OPCache Introduction

OPCache is produced Zend official, open and free opcode cache extension, also has a code optimization function, eliminating the overhead of each load and parse PHP scripts.

PHP 5.5.0 and later versions already bound OPcache extension.

Cache types of content:

  • OPCode

  • Interned String, such as comments, variable names, etc.

3. OPCache principle

OPCache caching mechanism is mainly: the operation code compiled into shared memory, providing access to other processes.

Here involves memory sharing mechanism, in addition to all memory resources operations have lock problems, we recite.

3.1 Shared Memory

UNIX / Linux system provides a variety of inter-process memory sharing method:

  • System-V shm API: System V shared memory,

    • sysv shm is persistent, unless explicitly delete a process, otherwise it is always present in memory until the system is shut down;

  • mmap API:

    • mmap mapped memory is not persistent, if the process is closed, then the mapping failure, unless already mapped on to a file

    • Mmap memory mapping mechanism is standard POSIX system calls, there are two kinds of anonymous file mapping and mapping

    • A major advantage is that mmap to map the file into the process address space

    • Avoiding data copying process from the user to the kernel buffer page cache buffer;

    • Of course, there is an advantage that does not require frequent read / write system call

  • POSIX API: System V shared memory is obsolete, POSIX shared memory provides a simpler, more rational design of API.

  • Unix socket API

Using the first three OPCache shared memory mechanism, in accordance with the default configuration or mmap shared memory mode.

PHP bytecode cache based on the scene, OPCache memory management design is very simple, fast read and write, do not release the memory, the data set to expire Wasted.

When Wasted memory is greater than the set value, the auto-restart mechanism OPCache, emptied and re-generate the cache.

3.2 mutex

The operation of any memory resources are related to the mechanism of the lock.

Shared memory: a unit of time, only allows a process to perform a write operation, allowing multiple processes to perform a read operation;

Write operations simultaneously, do not stop reading operation, so that there are few cases of deadlock.

This raises another problem: new code, flow scenarios, process execution queue buffer opcode operation; repeatedly written, resulting in waste of resources.

Advanced PHP architects >>> video, interview documentation free access docs.qq.com

4. OPCache cache reading

OPCache is the official Opcode caching solution, after PHP5.5 version, has been packaged into PHP source code distributed with.

PHP will produce compiled byte code and data cache to the shared memory at every request, read directly from the cache compiled opcode, execution.

By saving the script compilation process, improve the efficiency of PHP.

If you are using APC extension, do the same job, and now strongly recommended OPCache to replace, especially in PHP7.

4.1 OPCode Cache

Opcache caches OPCode as well as the following:

  • Functions PHP script involved

  • PHP scripts defined in Class

  • PHP script file path

  • PHP script OPArray

  • PHP script itself structure / content

4.2 Interned String cache

First, we need to understand what is Interned String?

In PHP5.4 when introduced Interned String mechanism to optimize PHP for storage and handling strings.

Especially when dealing with large pieces of string, such as PHP doces, Interned String can optimize memory.

Interned String cache contents include: variable names, class names, method names, strings, comments and so on.

In PHP-FPM mode, Interned String character cache is limited to internal Worker process.

The cached OPCache, then you can use the Interned String string buffer between Worker processes, saving memory.

We need to pay attention to a thing in PHP development in general, there will be a large segment of the comment will be cached in OPCache.

By php.ini configuration, turn off caching comment.

However, like Zend Framework and other frameworks, references notes, therefore, whether to close the comment cache needs to be treated differently.

5. OPCache update policy

A cache, there are expired and update strategies.

The OPCache updating strategy is very simple, the data set to expire Wasted, reaches the set value, empty the cache rebuild cache.

It should be noted: In high-traffic scene, rebuilding the cache is a very resource-intensive thing.

OPCache when creating the cache does not prevent other processes read.

This process will lead to a lot of repeated new cache. So, do not set an expiration time OPCache

Each time you publish a new code, the new case of repeated cache will appear. How to avoid it?

  • Do not release the code at its peak, which is in any case must abide by the rules of

  • Preheat the code, such as using PHP Scripts to tune access URL, or use OPCache API exposed as opcache_compile_file() compiled cache

6. OPCache configuration

6.1 Memory Configuration

  • opcache.preferred_memory_model="mmap" OPcache preferred memory modules. If left blank, OPcache will select the applicable module, under normal circumstances, is automatically selected to meet the demand. Possible values mmapare: , shm, posix and win32.

  • opcache.memory_consumption=64 OPcache shared memory size in megabytes, default64M

  • opcache.interned_strings_buffer=4 Size of the temporary memory used to store the string, in megabytes, the default4M

  • opcache.max_wasted_percentage=5 Waste memory limit, in percent. If you reach this limit, then OPcache will have to restart the renewal of the event. default5

6.2 The number of files and allows the cache size

  • opcache.max_accelerated_files=2000 Limit the number of OPcache script file can be stored in a hash table. The real value of the prime number set is { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } found greater than the first set value is equal to a prime number. Set the minimum value in the range is 200the maximum value is before the PHP 5.5.6 100000, and after the PHP 5.5.6 is 1000000. Defaults2000

  • opcache.max_file_size=0 Maximum file size in bytes of cache units. Set to 0 to cache all files. The default value 0

6.3 comments relevant cache

  • opcache.load_commentsboolean If disabled, even if the file contains notes, these notes will not load content. This option can be opcache.save_comments used together to achieve on-demand loading annotation content.

  • opcache.fast_shutdown boolean If enabled, it will be used to quickly stop the renewal of the event. The so-called quick-stop event is dependent on the renewal of the Zend Engine memory management module first released in memory of all requested variables, rather than turn to release each allocated memory block.

6.4 the secondary cache configuration

  • opcache.file_cache Configuring the secondary cache directory and enable L2 cache. Enable secondary cache memory can be filled in SHM, server reboot or reset SHM's time to improve performance. The default value is an empty string "", disable file-based caching.

  • opcache.file_cache_onlyboolean Enable or disable opcode cache in shared memory.

  • opcache.file_cache_consistency_checksboolean When a script is loaded from the file cache, whether the checksum file for verification.

  • opcache.file_cache_fallbackboolean On Windows platforms, when a process can not attach to shared memory when using a file-based cache, namely: opcache.file_cache_only=1. Enable file to be displayed cache.

Above hope to help everyone, many PHPer always encounter some problems and bottlenecks in the advanced time, write more business code no sense of direction, I do not know from where to start to ascend, which I compiled some information, including but not limited to: a distributed architecture, highly scalable, high-performance, high-concurrency, server performance tuning, TP6, laravel, YII2, Redis , Swoole, Swoft, Kafka, Mysql optimization, shell scripts, Docker, micro-services, Nginx , etc. more advanced knowledge required for advanced dry goods can be free for everyone to share,

Obtaining:

  1. Next Fanger Wei code scanning, keyword backstage reply

  2. Or    click here to train      train 2  

Released 2395 original articles · won praise 53 · views 440 000 +

Guess you like

Origin blog.csdn.net/lxw1844912514/article/details/105084430