search
HomeDatabaseRedisRedis stores logs and popular articles

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(&#39;log:key&#39;, $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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.