Introduction
This article mainly talks about the experience of using cache and the problems encountered in daily projects.
Directory
One: Basic writing method
Two: Cache avalanche
1: Global lock, instance lock
2: String lock
Three: Cache penetration
Four: Talk about cache avalanche again
Five: Summary
1: Basic writing method
For the convenience of demonstration, we use Runtime.Cache as the cache container and define a simple operation class. As follows:
public class CacheHelper { public static object Get(string cacheKey) { return HttpRuntime.Cache[cacheKey]; } public static void Add(string cacheKey, object obj, int cacheMinute) { HttpRuntime.Cache.Insert(cacheKey, obj, null, DateTime.Now.AddMinutes(cacheMinute), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } }
Simple reading:
public object GetMemberSigninDays1() { const int cacheTime = 5; const string cacheKey = "mushroomsir"; var cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 CacheHelper.Add(cacheKey, cacheValue, cacheTime); return cacheValue; }
In the project, there are many ways of writing like this. There is nothing wrong with writing this way, but there will be problems when the amount of concurrency increases. Continue reading
Two: Cache avalanche
Cache avalanche is due to cache invalidation (expiration) and the new cache has not yet expired.
In this intermediate period, all requests go to query the database, which puts huge pressure on the database CPU and memory. The number of front-end connections is not enough and the query is blocked.
This intermediate time is not that short, such as 1 second for SQL query, plus 0.5 seconds for transmission and analysis. That is to say, all user queries within 1.5 seconds directly query the database.
In this case, what we think of most is locking and queuing.
1: Global lock, instance lock
public static object obj1 = new object(); public object GetMemberSigninDays2() { const int cacheTime = 5; const string cacheKey = "mushroomsir"; var cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; //lock (obj1) //全局锁 //{ // cacheValue = CacheHelper.Get(cacheKey); // if (cacheValue != null) // return cacheValue; // cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 // CacheHelper.Add(cacheKey, cacheValue, cacheTime); //} lock (this) { cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 CacheHelper.Add(cacheKey, cacheValue, cacheTime); } return cacheValue; }
The first type: lock (obj1) is a global lock, but we have to declare an obj for each function, otherwise when the A and B functions both lock obj1, it will inevitably will cause one of them to block.
The second type: lock (this) locks the current instance and is invalid for other instances. This lock has no effect. You can lock using singleton mode.
But in the current instance: function A locks the current instance, and other functions that lock the current instance are also blocked in reading and writing. Undesirable
2: String lock
Since locking objects is not possible, we can directly lock the cache key by taking advantage of the characteristics of strings. Let’s take a look
public object GetMemberSigninDays3() { const int cacheTime = 5; const string cacheKey = "mushroomsir"; var cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; const string lockKey = cacheKey + "n(*≧▽≦*)n"; //lock (cacheKey) //{ // cacheValue = CacheHelper.Get(cacheKey); // if (cacheValue != null) // return cacheValue; // cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 // CacheHelper.Add(cacheKey, cacheValue, cacheTime); //} lock (lockKey) { cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 CacheHelper.Add(cacheKey, cacheValue, cacheTime); } return cacheValue; }
The first one: there is a problem with lock (cacheName), because the string is also shared and will block other operations using this string. For details, please see the previous blog post C# Language-Lock System in Multi-Threading (1).
2015-01-04 13:36 Update: Because strings are persisted by the common language runtime (CLR), this means that there is only one instance of any given string in the entire program. That’s why I use the second one
The second one: lock (lockKey) is enough. In fact, the purpose is to ensure the minimum granularity of the lock and global uniqueness, and only lock the currently cached query behavior.
Three: Cache penetration
A simple example: Generally, we cache user search results. If the database cannot query it, it will not be cached. But if you check this keyword frequently, you will check the database directly every time.
Cache is meaningless in this way. This is also a cache hit rate issue that is often raised.
public object GetMemberSigninDays4() { const int cacheTime = 5; const string cacheKey = "mushroomsir"; var cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; const string lockKey = cacheKey + "n(*≧▽≦*)n"; lock (lockKey) { cacheValue = CacheHelper.Get(cacheKey); if (cacheValue != null) return cacheValue; cacheValue = null; //数据库查询不到,为空。 //if (cacheValue2 == null) //{ // return null; //一般为空,不做缓存 //} if (cacheValue == null) { cacheValue = string.Empty; //如果发现为空,我设置个默认值,也缓存起来。 } CacheHelper.Add(cacheKey, cacheValue, cacheTime); } return cacheValue; }
In the example, we also cache the results that cannot be queried. This can avoid cache penetration when the query is empty.
Of course, we can also set up a separate cache area to perform first-level control verification. In order to distinguish it from normal cache.
四:再谈缓存雪崩
额 不是用加锁排队方式就解决了吗?其实加锁排队只是为了减轻DB压力,并没有提高系统吞吐量。
在高并发下: 缓存重建期间,你是锁着的,1000个请求999个都在阻塞的。 用户体验不好,还浪费资源:阻塞的线程本可以处理后续请求的。
public object GetMemberSigninDays5() { const int cacheTime = 5; const string cacheKey = "mushroomsir"; //缓存标记。 const string cacheSign = cacheKey + "_Sign"; var sign = CacheHelper.Get(cacheSign); //获取缓存值 var cacheValue = CacheHelper.Get(cacheKey); if (sign != null) return cacheValue; //未过期,直接返回。 lock (cacheSign) { sign = CacheHelper.Get(cacheSign); if (sign != null) return cacheValue; CacheHelper.Add(cacheSign, "1", cacheTime); ThreadPool.QueueUserWorkItem((arg) => { cacheValue = "395"; //这里一般是 sql查询数据。 例:395 签到天数 CacheHelper.Add(cacheKey, cacheValue, cacheTime*2); //日期设缓存时间的2倍,用于脏读。 }); } return cacheValue; }
代码中,我们多用个缓存标记key,双检锁校验。它设置为正常时间,过期后通知另外的线程去更新缓存数据。
而实际的缓存由于设置了2倍的时间,仍然可以能用脏数据给前端展现。
这样就能提高不少系统吞吐量了。
五:总结
补充下: 这里说的阻塞其他函数指的是,高并发下锁同一对象。
实际使用中,缓存层封装往往要复杂的多。 关于更新缓存,可以单开一个线程去专门跑这些,图方便就扔线程池吧。
具体使用场景,可根据实际用户量来平衡。

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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.


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

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.