Programming technology cache writing method (1)
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倍的时间,仍然可以能用脏数据给前端展现。
这样就能提高不少系统吞吐量了。
五:总结
补充下: 这里说的阻塞其他函数指的是,高并发下锁同一对象。
实际使用中,缓存层封装往往要复杂的多。 关于更新缓存,可以单开一个线程去专门跑这些,图方便就扔线程池吧。
具体使用场景,可根据实际用户量来平衡。

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



How to remove duplicate values from PHP array using regular expressions: Use regular expression /(.*)(.+)/i to match and replace duplicates. Iterate through the array elements and check for matches using preg_match. If it matches, skip the value; otherwise, add it to a new array with no duplicate values.

1. Programming can be used to develop various software and applications, including websites, mobile applications, games, and data analysis tools. Its application fields are very wide, covering almost all industries, including scientific research, health care, finance, education, entertainment, etc. 2. Learning programming can help us improve our problem-solving skills and logical thinking skills. During programming, we need to analyze and understand problems, find solutions, and translate them into code. This way of thinking can cultivate our analytical and abstract abilities and improve our ability to solve practical problems.

Build browser-based applications with Golang Golang combines with JavaScript to build dynamic front-end experiences. Install Golang: Visit https://golang.org/doc/install. Set up a Golang project: Create a file called main.go. Using GorillaWebToolkit: Add GorillaWebToolkit code to handle HTTP requests. Create HTML template: Create index.html in the templates subdirectory, which is the main template.

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Through GoGet, you can quickly and easily obtain Go modules. The steps are as follows: Run in the terminal: goget[module-path], where module-path is the module path. GoGet automatically downloads the module and its dependencies. The location of the installation is specified by the GOPATH environment variable.

Error handling in Go includes wrapping errors and unwrapping errors. Wrapping errors allows one error type to be wrapped with another, providing a richer context for the error. Expand errors and traverse the nested error chain to find the lowest-level error for easy debugging. By combining these two technologies, error conditions can be effectively handled, providing richer error context and better debugging capabilities.
