Explain the scene system from the principle of PHP cache technology


Cache has become an essential part of the project, it is the best way to improve performance, such as reducing network I / O, reducing disk I / O, etc., so that the project loading speed becomes faster.

Cache can be CPU cache, memory cache and hard disk cache, and different cache query speeds are different (CPU cache is better than memory cache than hard disk cache).

Next, I will introduce them one by one.

Browser cache
The browser stores the requested page in the client cache. When the visitor visits the page again, the browser can read the data directly from the client cache, which reduces the access to the server and speeds up the loading speed of the web page.

Strong cache
The request sent by the user is directly obtained from the client cache and does not request the server.

According to expires and cache control, determine whether to hit the strong cache.

The code is as follows:

header(‘Expires: ‘. gmdate(‘D, d M Y H:i:s’, time() + 3600). ‘ GMT’);

Header (“cache control: Max age = 3600”); / / valid for 3600 seconds

Cache control can also set the following parameters:

Public: can be cached by all users (end user’s browser / CDN server)

Private: can only be cached by the end user’s browser

No cache: do not use local cache

No store: disable caching data

Negotiation cache
The user sends the request to the server, and the server decides whether to use the client cache.

The code is as follows:

$last_modify = strtotime($_SERVER[‘HTTP_IF_MODIFIED_SINCE’]);

if (time() – $last_modify < 3600) {

header(‘Last-Modified: ‘. gmdate(‘D, d M Y H:i:s’, $last_modify).’ GMT’);

header(‘HTTP/1.1 304’); //Not Modified



header(‘Last-Modified: ‘. gmdate(‘D, d M Y H:i:s’).’ GMT’);

The effect of user’s operation behavior on cache
Expires last modified
Address bar enter valid
Page Jump valid
New window is valid
Forward / backward valid
F5 refresh is invalid and valid
Invalid Ctrl + F5 refresh
File cache
Data file cache
Cache the data with low update frequency and high read frequency into files.

For example, multiple places in the project use city data for three-level linkage. We can cache the city data into a file (city_data. JSON). JS can read the file directly without requesting the back-end server.

Stationization of the whole station
CMS (content management system), maybe everyone is familiar with it. For example, in the early Dede and phpcms, static HTML can be set in the background. When users visit the website, they read static HTML without requesting the back-end database or ajax data interface, which speeds up the loading speed of the website.

Static HTML has the following advantages:

Good for SEO

Fast page opening

Reduce server burden

CDN cache
CDN (content delivery network) content distribution network.

When users visit the website, they automatically select the content of the nearest CDN node, without requesting the source server, which speeds up the opening of the website.

Cache mainly includes HTML, image, CSS, JS, XML and other static resources.

NoSQL cache
Memcached cache
Memcached is a high-performance distributed memory cache server.

The general purpose is to reduce the number of database accesses by caching the database query results, so as to improve the speed and scalability of dynamic web applications.

It can also be used to store data of various formats, including images, videos, files, etc.

Memcached only supports K / V type data and does not support persistent storage.

The difference between Memcache and memcached

Memcached starts from 0.2.0, requires PHP version > = 5.2.0, and Memcache requires PHP version > = 4.3.

The final release time of memcached is December 24, 2018, and the final release time of Memcache is April 7, 2013.

Memcached is based on libmemcached and Memcache is based on PECL extension.

You can think of memcached as an upgrade of Memcache.

PHP memcached user manual:


Memcached is often compared with redis. Next, we will introduce redis cache.

Redis cache
Redis is a high-performance K / V database.

Redis largely compensates for the lack of memcached K / V storage, such as list (linked list), set (set), Zset (ordered set), hash (hash). It can not only store data in memory, but also persist data to disk, supporting master-slave synchronization.

In general, redis can be regarded as an extension of memcached, which is more heavyweight and powerful.

Redis is mostly used in daily work.

Redis learning website: http://www.redis.cn/

Mongodb cache
Mongodb is a database based on distributed file storage. Written in C + +.

It aims to provide scalable high-performance data storage solutions for web applications.

Mongodb is a product between relational database and non relational database. It has the most abundant functions and is the most like relational database.

Mongodb learning website: http://www.mongodb.org.cn

Web server cache
Apache cache
With mod_expires, you can specify the expiration time of the cache, and cache HTML, pictures, JS, CSS, etc.

Open http.conf and open the module:

LoadModule expires_module modules/mod_expires .so

Specify cache expiration time:

<IfModule expires_module>

Open cache

ExpiresActive on

CSS cache (8640000 seconds = 10 days)

ExpiresByType text/css A8640000

JS cache

ExpiresByType application/x-javascript A8640000

ExpiresByType application/javascript A8640000

HTML cache

ExpiresByType text/html A8640000

Picture cache

ExpiresByType image/jpeg A8640000

ExpiresByType image/gif A8640000

ExpiresByType image/png A8640000

ExpiresByType image/x-icon A8640000


Nginx cache
Use the expire parameter to specify the expiration time of the cache, which can cache HTML, pictures, JS, CSS, etc.

Open nginx.conf:

//Take the picture as an example:

Location ~. (gif|jpg|jepg|png|bmp|ico) ${add a new location

root html;

Expires 1D; specifies the cache time


You can also understand the following: proxy cache path and proxy cache to set the cache.

Opcode cache
Opcode (operate code) opcode.

After the PHP program runs, all the memory will be released immediately. All the variables in the program will be destroyed. Every request will be retranslated and executed, resulting in slow speed.

When the interpreter finishes analyzing the script code, it generates the intermediate code that can run directly, also known as the opcode.

The purpose of opcode is to avoid repeated compilation and reduce CPU and memory overhead.

APC cache
APC (alternative PHP cache) optional PHP cache.

APC aims to provide a free, open and sound framework for caching and optimizing PHP intermediate code.

APC can eliminate the time of PHP dynamic parsing and compiling, so that PHP scripts can execute faster.

The final release time of APC extension is 2012-09-03.

If you are interested, you can learn about it. Official introduction: http://php.net/manual/zh/book

eAccelerator:A PHP opcode cache。

If you are interested, you can learn about it. Official introduction: http://eaccelerator.net/

Xcache is a fast and stable PHP opcode buffer.

You can learn about it if you are interested. Official introduction: http://xcache.lighttpd.net/

This paper mainly introduces browser cache, file cache, NoSQL cache, web server cache, opcode cache.

Each kind of cache can be studied in depth, from introduction, installation, use, and summary of application scenarios.

You can think about, through the above introduction, what kind of cache do we use in our work?

What other caches can be used to help our project?

Frequently asked questions about caching
After using cache, you must have encountered some headache problems, such as data consistency, avalanche, hot data cache, cache monitoring, etc.

Here are a few questions for you. It’s just a diversion.

When caching is used in projects, we choose redis or memcached. Why?
Some scenarios:

1、 For example, to achieve a simple log collection function or send a large number of SMS, e-mail function, the implementation method is to first collect data into the queue, and then there is a scheduled task to consume the queue to deal with the things to be done.

Use redis’s lpush, rpop or rpush, lpop directly.

/ / queue

$redis->lpush(key, value);

/ / outgoing queue


Memcached does not have this data structure.

2、 For example, we need to store user information, ID, name, phone, age, height, how to store?

Scheme 1: key = > value

Key = UserData user ID

Value = json_encode (user data)

When querying, take out the key first, and then parse it with JSON \.

Scheme 2: hash

Key = UserData user ID

Hashkey = name, value = XX

Hashkey = phone, value = XX

Hashkey = age, value = XX

Hashkey = height, value = XX

When querying, just take out the key.

/ / add

$redis->hSet(key, hashKey, value);

$redis->hSet(key, hashKey, value);

$redis->hSet(key, hashKey, value);

/ / Editor

$redis->hSet(key, hashKey, value);

/ / query

$redis – > hgetall (key); / / query all attributes

$redis – > hget (key, hashkey); / / query a property

Scheme 2 is better than scheme 1.

3、 For example, social projects are similar to Sina Weibo, personal center’s focus list and fans list, two-way focus list, popular Weibo, and news subscription.

The above data structure provided by redis can be used.

4、 Memcached is only stored in memory, while redis can be stored in memory or persisted to disk.

If the data in the requirement needs to be persisted, please select redis.

Memcached is not used in personal work, and it is better than redis when memcached memory allocation is obtained by querying data.

Memcached uses the slab allocation mechanism to manage the memory by default. According to the predetermined size, the allocated memory is divided into specific length blocks to store the corresponding length of key value data records, so as to completely solve the memory fragmentation problem.

How to ensure data consistency between cache and database?
New data: first add to the database, then add to the cache.

Edit data: delete the cached data, modify the data in the database, and then add it to the cache.

Delete data: delete the cached data first, and then delete the data in the database.

Query data: first query the cache data, no, then query the database, and then add to the cache.

Strong consistency is hard to guarantee, such as transaction consistency, point in time consistency, and final consistency.

Analyze the specific problems.

What about cache penetration?
The user requests data that does not exist in the cache, causing the request to fall directly on the database.

1、 Set the key value with rules. First verify whether the key meets the specifications.

2、 Interface current limiting, degradation and fusing, please study istio: https://istio.io/

3、 Bloom filter.

4、 Set the empty cache and expiration time for the key value that does not exist. If the storage layer creates data, update the cache in time.

What about avalanches?
1、 Mutex. Only one request is allowed to rebuild the index. Other requests wait for the cache reconstruction to finish and get data from the cache again.

Recommended Today

Processing entry for ABAP, ui5 and webpack

ABAP The first implementation is initialization: UI5 If a ui5 application is configured in the Fiori launchpad of the portal, the entry of the application is Component.jsAnother method (mostly used for normal testing and verification purposes) does not need launchpad, but only needs to create a new component running environment (shell) in a standalone HTML:See […]