PHP+redis implements full-page caching system
Recommended: "PHP Video Tutorial" "redis Tutorial》
php redis implements a full-page cache system
A function mentioned in a previous project requires pre-stored page information in the background Put it in the database, such as the app's registration agreement, user agreement, etc. Then write it into a php page, and the app accesses this page when calling the interface. At that time, I discovered a problem. These agreements are often modified only once every few months. , and every time the user views these protocols, nginx will re-read the file from the database, and the speed will be very slow.
The following picture m_about.php is the data page I generated,
It takes 2.4s to load it from the database and regenerate the file in the virtual machine environment (of course the actual test environment will be faster).
Since this kind of page data is updated Less, why not cache it? I thought of a full page cache system (full page cache) in the common redis applications I looked at before. Why not write one and give it a try.
Code Ideas
Redis uses the phpredis extension. Of course, you can also use the predis extension. You just need to change a few read functions.
Regarding the interface of the cache system, I refer to the cache in laravel here. System. I think the design interface of this system is very clear. It not only includes redis, but also can use files, mysql, memcache.
Of course, the full page cache does not use so many things. I just borrowed his Function design. The first is the function getUrlText, which is to get the data of the whole page. I didn’t think too much here. I just use file_get_contents directly. Of course, you can also rewrite it into a curl function
/** * 获取对应的url的信息 * @param string $url 对应的地址 * @return boolean|string */ public function getUrlText($url) { if (empty($url)) { return false; } return file_get_contents($url); }
. Secondly, there are several functions that draw lessons from the cache system. , remember function, memory cache, this is the most important interface to the outside world, generally use it directly in the cache system.
/** * 记录对应的缓存,如果之前存在则返回原本的缓存 * @param string $cacheName 缓存名 * @param string | callback $urlOrCallback 需要缓存的数据地址.可以是一个 网页地址也一个可回调类型,如果不是可回调类型,则判定是一个网址 * @param null | int $ttl 缓存过期时间,如果不过期就是用默认值null * @throws \Exception 如果无法访问地址 * @return boolean|string 缓存成功返回获取到的页面地址 */ public function remember($cacheName, $urlOrCallback, $ttl = null) { $value = $this->get($cacheName);//检查缓存是否存在 if (!$value) { //之前没有使用键 if (is_callable($urlOrCallback)) { $text = $urlOrCallback(); } else { //如果不是回调类型,则尝试读取网址 $text = $this->getUrlText($urlOrCallback); } if (empty($text)) { throw new \Exception('can not get value:' . $urlOrCallback); } $this->put($cacheName, $text, $ttl); return $text; } else { return $value; } }
refresh function, refresh cache function, if the cache page has been updated, go Refresh it.
/** * 更新缓存,并返回当前的缓存 * @param string $cacheName 缓存名 * @param string | callback $urlOrCallback 需要缓存的数据地址.可以是一个 网页地址也一个可回调类型,如果不是可回调类型,则判定是一个网址 * @param null | int $ttl 过期时间,如果不过期就是用默认值null * @return boolean|string 缓存成功返回获取到的页面地址 */ public function refresh($cacheName, $urlOrCallback, $ttl = null) { $this->delete($cacheName); return $this->remember($cacheName, $urlOrCallback, $ttl); }
The remaining two code files. One is redisFPC.php, which is the demo of full page cache, and the other is the file for testing
fpcTest.php
Here is the use The one is github, connected to my own git blog. If there is a problem connecting to github, you can see the complete code given at the end of this article.
test
We are here Test, the first load is slower because it needs to read the corresponding m_ahout information
The second load is much faster because it is read from redislimian
Usage suggestions
I think the code has given enough interfaces. Use the remember function to record the cache when caching for the first time. , then if the cache changes, use the refresh function to update the cache. If possible, try to use ttl to set the cache expiration time.
Full code
redisFPC. php
<?php namespace RedisFPC; class RedisFPC { /** * php redis的访问类 * @var unknown */ private $redis; /** * 构造函数 * @param array $redis 使用phpredis的类 * @param 是否连接成功 */ public function __construct($redis = []) { //$this->redis = $redis; $this->redis = new \Redis(); return $this->redis->connect('127.0.0.1'); } /** * 记录对应的缓存,如果之前存在则返回原本的缓存 * @param string $cacheName 缓存名 * @param string | callback $urlOrCallback 需要缓存的数据地址.可以是一个 网页地址也一个可回调类型,如果不是可回调类型,则判定是一个网址 * @param null | int $ttl 缓存过期时间,如果不过期就是用默认值null * @throws \Exception 如果无法访问地址 * @return boolean|string 缓存成功返回获取到的页面地址 */ public function remember($cacheName, $urlOrCallback, $ttl = null) { $value = $this->get($cacheName);//检查缓存是否存在 if (!$value) { //之前没有使用键 if (is_callable($urlOrCallback)) { $text = $urlOrCallback(); } else { //如果不是回调类型,则尝试读取网址 $text = $this->getUrlText($urlOrCallback); } if (empty($text)) { throw new \Exception('can not get value:' . $urlOrCallback); } $this->put($cacheName, $text, $ttl); return $text; } else { return $value; } } /** * 获取对应的缓存值 * @param string $cacheName 缓存名 * @return String | Bool,如果不存在返回false,否则返回对应的缓存页信息 */ public function get($cacheName) { return $this->redis->get($this->getKey($cacheName)); } /** * 将对应的全页缓存保存到对应redis中 * @param string $cacheName 缓存名 * @param string $value * @param null | int $ttl 过期时间,如果不过期就是用默认值null * @return boolean 保存成功返回true */ public function put($cacheName, $value, $ttl = null) { if (is_null($ttl)) { return $this->redis->set($this->getKey($cacheName), $value); } else { return $this->redis->set($this->getKey($cacheName), $value, $ttl); } } /** * 删除对应缓存 * @param string $cacheName 缓存名 */ public function delete($cacheName) { return $this->redis->delete($this->getKey($cacheName)); } /** * 更新缓存,并返回当前的缓存 * @param string $cacheName 缓存名 * @param string | callback $urlOrCallback 需要缓存的数据地址.可以是一个 网页地址也一个可回调类型,如果不是可回调类型,则判定是一个网址 * @param null | int $ttl 过期时间,如果不过期就是用默认值null * @return boolean|string 缓存成功返回获取到的页面地址 */ public function refresh($cacheName, $urlOrCallback, $ttl = null) { $this->delete($cacheName); return $this->remember($cacheName, $urlOrCallback, $ttl); } /** * 获取对应的url的信息 * @param string $url 对应的地址 * @return boolean|string */ public function getUrlText($url) { if (empty($url)) { return false; } return file_get_contents($url); } /** * 生成全页缓存键名 * @param string $cacheName 需要缓存的名称 * @return string 对应的在redis中的键名 */ private function getKey($cacheName) { return 'FPC:'. $cacheName; } }
Test code for testing
Note that the url here is the local cache url
<?php use RedisFPC\RedisFPC; require_once 'redisFPC.php'; /* $text = file_get_contents('http://localhost:1002/m_about.php'); var_dump($text); */ $url = 'http://localhost:1002/m_about.php'; $fpc = new RedisFPC(); echo $fpc->remember('服务协议', $url, 60*60*24);
The above is the detailed content of PHP+redis implements full-page caching system. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.
