Home >Backend Development >PHP Tutorial >Learn more about caching technology in PHP

Learn more about caching technology in PHP

青灯夜游
青灯夜游forward
2021-07-14 19:24:466207browse

Caching has become an essential part of the project, and it is the best way to improve performance. The following article will take you to learn more about caching technology in PHP.

Learn more about caching technology in PHP

Caching is the best way to improve performance, such as reducing network I/O, reducing disk I/O, etc., to make project loading faster.

The cache can be CPU cache, memory cache, or hard disk cache. Different caches have different query speeds (CPU cache > Memory cache > Hard disk cache).

Next, let me introduce them one by one.

Browser Cache

The browser stores the requested page in the client cache. When the visitor visits this page again, the browser can directly access it from Reading data from the client cache reduces access to the server and speeds up the loading of web pages.

Strong Cache

Requests sent by users are obtained directly from the client cache without requesting the server.

Determine whether the strong cache is hit based on Expires and Cache-Control.

The code is as follows:

header('Expires: '. gmdate('D, d M Y H:i:s', time() + 3600). ' GMT');
header("Cache-Control: max-age=3600"); //有效期3600秒

Cache-Control You 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: does not use local cache
  • no-store: prohibits caching of data

Negotiation cache

The request sent by the user is sent to the server, and the server determines whether to use client cache.

The code is as follows:

$last_modify = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if (time() - $last_modify < 3600) {
    header(&#39;Last-Modified: &#39;. gmdate(&#39;D, d M Y H:i:s&#39;, $last_modify).&#39; GMT&#39;);
    header(&#39;HTTP/1.1 304&#39;); //Not Modified
    exit;
}
header(&#39;Last-Modified: &#39;. gmdate(&#39;D, d M Y H:i:s&#39;).&#39; GMT&#39;);

The impact of user operation behavior on cache

Learn more about caching technology in PHP

File cache

Data file cache

will update data with low update frequency and high read frequency, Cache to file.

For example, if city data is used for three-level linkage in multiple places in the project, we can cache the city data into a file (city_data.json), and JS can directly read this file without requesting the backend. server.

Static throughout the site

CMS (content management system), perhaps everyone is familiar with it, such as the early DEDE and PHPCMS, and static HTML can be set in the background. When users access the website, all they read is static HTML. There is no need to request the back-end database or the Ajax request data interface, which speeds up the loading speed of the website.

Static HTML has the following advantages:

    It is conducive to search engine inclusion (SEO)
  • The page opens quickly
  • Reduces the load on the server

CDN Cache

CDN (Content Delivery Network) content delivery network.

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

The cache mainly includes static resources such as HTML, images, CSS, JS, and XML.

NoSQL Cache

Memcached Cache

Memcached is a high-performance distributed memory cache server.

The general purpose of use is to reduce the number of database accesses by caching database query results to increase the speed and scalability of dynamic web applications.

It can also be used to store data in 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 starting from 0.2.0 requires PHP version >=5.2.0, Memcache requires PHP version >= 4.3.
  • Memcached was last released on 2018-12-24, and Memcache was last released on 2013-04-07.
  • Memcached is based on libmemcached, and Memcache is based on PECL extension.
You can think of Memcached as an upgraded version of Memcache.

PHP Memcached User Manual:

http://www.php.net/manual/zh/book.memcached.php

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 shortcomings of Memcached K/V storage, such as List (linked list), Set (set), Zset (ordered set), Hash (hash), which can store data in In memory, data can also be persisted to disk, supporting master-slave synchronization.

In general, Redis can be regarded as an extended version of Memcached, more heavyweight and more powerful.

Redis is mostly used in daily work.

MongoDB Cache

MongoDB is a database based on distributed file storage. Written in C language.

旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

WEB服务器缓存

Apache缓存

利用 mod_expires ,指定缓存的过期时间,可以缓存HTML、图片、JS、CSS 等。

打开 http.conf,开启模块:

LoadModule expires_module modules/mod_expires.so

指定缓存的过期时间:

<IfModule expires_module>
     #打开缓存
     ExpiresActive on 

     #css缓存(8640000秒=10天)
     ExpiresByType text/css A8640000

     #js缓存
     ExpiresByType application/x-javascript A8640000
     ExpiresByType application/javascript A8640000

     #html缓存
     ExpiresByType text/html A8640000

     #图片缓存
     ExpiresByType image/jpeg A8640000
     ExpiresByType image/gif A8640000
     ExpiresByType image/png A8640000
     ExpiresByType image/x-icon A8640000

 </IfModule>

Nginx缓存

利用 expire 参数,指定缓存的过期时间,可以缓存HTML、图片、JS、CSS 等。

打开 nginx.conf

//以图片为例:
location ~\.(gif|jpg|jepg|png|bmp|ico)$ { #加入新的location
    root html;
    expires 1d; #指定缓存时间
}

大家也可以了解下:proxy_cache_path 和 proxy_cache,进行缓存的设置。

Opcode缓存

Opcode(Operate Code)操作码。

PHP程序运行完后,马上释放所有内存,所有程序中的变量都销毁,每次请求都要重新翻译、执行,导致速度可能会偏慢。

当解释器完成对脚本代码的分析后,便将它们生成可以直接运行的中间代码,也称为操作码。

操作码 的目地是避免重复编译,减少CPU和内存开销。

APC缓存

APC(Alternative PHP Cache)可选 PHP 缓存。

APC 的目标是提供一个自由、 开放,和健全的框架,用于缓存、优化 PHP 中间代码。

APC 可以去掉 php 动态解析以及编译的时间,使php脚本可以执行的更快。

APC 扩展最后的发布时间为 2012-09-03。

感兴趣可以了解下,官方介绍:http://php.net/manual/zh/book.apc.php

eAccelerator

eAccelerator:A PHP opcode cache。

感兴趣可以了解下,官方介绍:http://eaccelerator.net/

XCache

XCache 是一个又快又稳定的 PHP opcode 缓存器。

感兴趣可以了解下,官方介绍:http://xcache.lighttpd.net/

小结

文章主要简单的介绍了 浏览器缓存、文件缓存、NoSQL缓存、WEB服务器缓存、Opcode缓存。

每一种缓存都可以深入研究,从介绍 -> 安装 -> 使用 -> 总结应用场景。

大家可以思考下,通过上面的介绍,工作中我们使用了哪些缓存?

还可以再使用哪些缓存,可以对我们的项目有帮助?

关于缓存的常见问题

用过缓存,大家肯定遇到过比较头痛的问题,比如数据一致性,雪崩,热点数据缓存,缓存监控等等。

给大家列出几个问题,纯属抛转引玉。

当项目中使用到缓存,我们是选择 Redis 还是 Memcached ,为什么?

举一些场景:

一、比如实现一个简单的日志收集功能或发送大量短信、邮件的功能,实现方式是先将数据收集到队列中,然后有一个定时任务去消耗队列,处理该做的事情。

直接使用 Redis 的 lpush,rpop 或 rpush,lpop。

//进队列
$redis->lpush(key, value);

//出队列
$redis->rpop(key);

Memcached 没有这种数据结构。

二、比如我们要存储用户信息,ID、姓名、电话、年龄、身高 ,怎么存储?

方案一:key => value

key = user_data_用户ID

value = json_encode(用户数据)

查询时,先取出key,然后进行json_decode解析。

方案二:hash

key = user_data_用户ID

hashKey = 姓名,value = xx

hashKey = 电话,value = xx

hashKey = 年龄,value = xx

hashKey = 身高,value = xx

查询时,取出key即可。

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

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

//查询
$redis->hGetAll(key); //查询所有属性
$redis->hGet(key, hashKey); //查询某个属性

方案二 优于 方案一。

三、比如社交项目类似于新浪微博,个人中心的关注列表和粉丝列表,双向关注列表,还有热门微博,还有消息订阅 等等。

以上都用 Redis 提供的相关数据结构即可。

四、Memcached 只存储在内存中,而 Redis 既可以存储在内存中,也可以持久化到磁盘上。

如果需求中的数据需要持久化,请选择 Redis 。

个人在工作中没有用到 Memcached ,通过查询资料得到 Memcached 内存分配时优于 Redis。

Memcached 默认使用 Slab Allocation 机制管理内存,按照预先规定的大小,将分配的内存分割成特定长度的块以存储相应长度的key-value数据记录,以完全解决内存碎片问题。

如何保证,缓存与数据库的数据一致性?

新增数据:先新增到数据库,再新增到缓存。

编辑数据:先删除缓存数据,再修改数据库中数据,再新增到缓存。

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

Query data: First query the cache data, if there is none, then query the database, and then add it to the cache.

Strong consistency is difficult to guarantee, such as transaction consistency, point-in-time consistency, final consistency, etc.

Let’s analyze specific issues in detail.

What to do 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 a regular Key value and first verify whether the Key complies with the specification.

2. For interface current limiting, downgrading, and circuit breaker, please study istio: istio.io/

3. Bloom filter.

4. Set an empty cache and expiration time for non-existent key values. If the storage layer creates data, update the cache in a timely manner.

What to do about an avalanche?

1. Mutex lock, only one request is allowed to rebuild the index. Other requests wait for the cache reconstruction to be completed and re-obtain data from the cache.

2. Double cache strategy, original cache and copy cache. When the original cache fails and requests the copy cache, the original cache expiration time is set to short-term and the copy cache is set to long-term.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Learn more about caching technology in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:zhihu.com. If there is any infringement, please contact admin@php.cn delete