A variety of data structures can be implemented using the Redis list data type, which can be regarded as an index array in PHP. It can implement a variety of data structures such as stacks, queues, and message queues. Today, I would like to introduce to you how to use redis to save system logs and popular article lists.
Storing logs
As we all know, nginx logs will not be automatically cut by default. They will always be stored in a file and appended to. We need to do the log cutting operation ourselves. In addition to nginx, logs are used in many places. When something goes wrong, logs are one of the main ways we look for clues.
We now plan to write the system logs to redis. Daily logs will be recorded in a list to prevent a single log file from being too large.
The basic idea is to write daily log information into a separate list, and then do a scheduled task. The function of the scheduled task is to take out the log list from 1 month ago and persist it. to a text file, and then delete the log list from 1 month ago in redis to prevent redis from occupying too much memory.
You can use the compression function to compress log information and reduce memory usage. In addition, maintain a list to store the key names of the log list to facilitate retrieving the key names of the log list. The pseudocode for storing logs is as follows:
$log = ... // 日志信息 // 日志列表键名 $key = 'log:'.strtotime(date('Y-m-d')); // 维护一个键名列表 if (!$redis->exists($key)) { $listlogkey = 'log:key'; $redis->rpush($listlogkey, $key); } // 日志信息存放到redis中 $redis->rpush($key, $log);
The scheduled task code is as follows:
$lastMonth = strtotime("-30 day"); while ($logkey = $redis->lpop('log:key')) { $logTime = explode(':', $logkey)[1]; if ($logTime < $lastMonth) { // 从日志列表里去日志信息,一次取50条 for ($start = 0, $end = 49;true;$start +=50, $end+=50) { $logs = $redis->lrange($logkey, $start, $end); if (!$logs) break; // 将日志信息解压缩,然后追加写入文本文件中 …… // 删除该日志列表 $redis->del($logkey); } } else { // 一个月之内的,重新push到左侧 $redis->lpush('log:key', $logkey); exit; } }
There are a few points to note here. If the persistent log fails, or it is a log within the past month, you need to Re-push the log list key name from the left. In addition, when fetching logs from the log list, do not fetch them all at once, as this may easily lead to redis blocking. Each time, take a certain number (such as 50) and take them out in a loop.
Storing popular news IDs
I won’t post the code here, but mainly talk about the ideas. I used to create a system with a menu function, including today's hottest, hottest week, and hottest in January. At that time, our website had quite a lot of traffic, but within a few days, the website went down. The reason is that mysql's slow query problem. Because this piece of SQL includes grouping, COUNT(), conditional judgment, etc.
Let me tell you about our solution: write a mysql stored procedure and call the stored procedure regularly. The function of this stored procedure is to filter out the most popular articles today, this week, and January, take 100 article IDs respectively, and store their article IDs in the redis queue. For the most popular articles, we only display the top 100. In this way, our system will have no slow queries.
The above is the detailed content of Redis stores logs and popular articles. For more information, please follow other related articles on the PHP Chinese website!

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.


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

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),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.

SublimeText3 Chinese version
Chinese version, very easy to use