Cache breakdown
The difference from cache penetration is that cache breakdown refers to hot data that is not in the cache but exists in the database.
For example: hot news on the homepage, hot data with a very large number of concurrent visits, if the cache expires and fails, the server will query the DB. At this time, if a large number of concurrent queries are made to the DB, the DB may be overwhelmed instantly.
Drawed a simple diagram, as shown below:
Solution: DB query plus distributed lock.
Unlocked situation
Before solving the problem, first take a look at the unprocessed code and operation conditions.
Query product details code based on product ID
Clear the Redis cache and open 5 threads for concurrent access testing. The test code is as follows :
We expected that the DB would only be queried once, and the next four queries would be fetched from the Redis cache, but the result was:
There is no distributed lock, and the result is expected. However, the container puts a lot of pressure on the DB.
If it is a single server, just use Java's synchronization lock directly
Unfortunately, usually after The client will deploy a cluster, and Java's synchronization lock cannot implement distributed locks.
Redis distributed lock solves cache breakdown
Java's built-in lock can only be applied on a single machine and cannot be distributed. It can be achieved using Redis. Distributed lock.
Code after adding distributed lock
//根据ID查询商品 @GetMapping("/{id}") public R id(@PathVariable String id){ //先查Redis缓存 Object o = redisTemplate.opsForValue().get(id); if (o != null) { //命中缓存 System.err.println("id:"+id+",命中redis缓存..."); return R.success(o); } //缓存未命中 查询数据库 String lockKey = "lock" + id; //加锁,10s后过期 for (;;) { if (redisTemplate.opsForValue().setIfAbsent(lockKey, System.currentTimeMillis(), 10L, TimeUnit.SECONDS)) { //加锁成功的线程,再次检查 o = redisTemplate.opsForValue().get(id); if (o != null) { //命中缓存 System.err.println("Thread:" + Thread.currentThread().getName() + ",id:"+id+",命中redis缓存..."); //释放锁 redisTemplate.delete(lockKey); return R.success(o); } //仍未命中 System.err.println("Thread:" + Thread.currentThread().getName() + ",id:" + id + ",查询DB..."); Goods goods = goodsMapper.selectById(id); //结果存入Redis redisTemplate.opsForValue().set(id, goods); //释放锁 redisTemplate.delete(lockKey); return R.success(goods); } //竞争不到锁,暂时让出CPU资源 Thread.yield(); } }
Start 5 threads for concurrent access. The result is as follows:
The above is the detailed content of How Redis distributed lock prevents cache breakdown. For more information, please follow other related articles on the PHP Chinese website!

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

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,


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

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SublimeText3 Chinese version
Chinese version, very easy to use

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software