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.
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('Last-Modified: '. gmdate('D, d M Y H:i:s', $last_modify).' GMT'); header('HTTP/1.1 304'); //Not Modified exit; } header('Last-Modified: '. gmdate('D, d M Y H:i:s').' GMT');
The impact of user operation behavior on cache
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.
PHP Memcached User Manual: http://www.php.net/manual/zh/book.memcached.phpMemcached 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: https://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!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),