search
HomeDatabaseRedisHow to use Redis to solve high concurrency

NoSQL

Abbreviation for Not Only SQL. NoSQL was proposed to solve the inability of traditional RDBMS to deal with certain problems.

That is, non-relational databases. They do not guarantee the ACID characteristics of relational data. There is generally no correlation between data. They are very easy to implement in terms of expansion and have high performance.

Redis

Redis is a typical representative of nosql and is also a must-use technology for current Internet companies.

Redis mainly uses hash tables to implement key-value pair storage. Most of the time, it is used directly in the form of cache, so that the request does not directly access the disk, so the efficiency is very good, and it can fully meet the needs of small and medium-sized enterprises.

Common data types

  • String string

  • Hash hash

  • List list

  • ##sets sets

  • Ordered set sort set

String and hash are used more frequently. Each type has its own operation command, which is nothing more than adding, deleting, modifying and checking. I will sort out the specific commands later.

Pain Points

When many requests occur simultaneously in web applications, it may cause errors in data reading and storage, that is, dirty reads and dirty data generation occur.

Under distributed projects, more problems will arise.

Thoughts

When it comes to concurrency, the essence is that multiple requests come in at the same time and cannot be processed correctly.

You can put all requests in a queue, so that the requests can come in one by one in order to execute the business logic. Using message queues is currently a feasible solution. I will compile an article on how to deal with high concurrency message queues next time

Another method is to directly convert parallelism to serialization. Java provides synchronized. That is synchronization, but this is still not a suitable solution in places with strict efficiency requirements or distributed projects. This leads to the use of redis to implement distributed locks to solve concurrency problems.

Distributed lock

In distributed projects, a unique, universal, and efficient identifier is used to represent locking and unlocking.

Redis is very simple to implement, that is, whether a key exists or not indicates whether it is locked or unlocked.

Take the string type as an example:

Integer stock = goodsMapper.getStock();
if (stock > 0) {
    stock =- 1;
    goodsMapper.updateStock(stock);
}

The above is the simplest pseudo code for instant killing. We try to use redis to implement distributed locks.

// 这里是错误代码,只是一个思考过程,请耐心看完哦
String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
String value = jedisUtils.get(key);
if (value != null) { // 未上锁
    // wingzingliu
    jedisUtils.set(key, 1); // 上锁
    Integer stock = goodsMapper.getStock();
    if (stock > 0) {
        stock =- 1;
        goodsMapper.updateStock(stock);
        jedisUtils.del(key); // 释放锁
    }
}

There may be a problem with the above code, that is, when multiple requests come in at the same time, and multiple requests at a certain time all get the value as empty, thread A enters the if and goes to // wingzingliu. Locking, other requests also come in, so dirty data will appear.

The code problem here is that the atomicity issue is not considered.

So we have to use a setNx command of redis. The essence is to set the value, but this is an atomic operation. After execution, it will return whether the setting is successful.

redis> SETNX job "programmer"    # job 设置成功
(integer) 1
 
redis> SETNX job "code-farmer"   # 尝试覆盖 job ,失败
(integer) 0
 
redis> GET job                   # 没有被覆盖
"programmer"

Focus on when there is a value, it will fail and return 0. So our code will be transformed into the following.

// 这里是错误代码,只是一个思考过程,请耐心看完哦
String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
Long result = jedisUtils.setNx(key, 1);
if (result > 0) { // 上锁成功,进入逻辑
    // wingzingliu1
    Integer stock = goodsMapper.getStock();
    if (stock > 0) {
        stock =- 1;
        goodsMapper.updateStock(stock);
 
        System.out.println("购买成功!");
    } else {
        System.out.println("没有库存了!");
    }
    // wingzingliu2
    jedisUtils.del(key); // 释放锁
}

With the above, we can ensure atomicity and process them correctly in order.

But there is another hidden problem, that is, after a thread successfully executes the lock, the program throws an exception between wingzingliu1 and wingzingliu2. Then the program terminates and the lock cannot be released. Other threads They can't even get in.

The solution is to add a try catch finally block and release the lock in finally.

But what if it is down? After the lock is locked, the machine crashes. The finally contents will still not be executed. The lock is not released. Without manual processing, all threads will not be able to enter in the future.

So the expiration time of redis is introduced, and it will be automatically unlocked at a certain time.

// 这里是不够完善的代码,请耐心看完哦
try {
    String key = "REDIS_DISTRIBUTION_LOCKER"; // 分布式锁名称
    Long result = jedisUtils.setNx(key, 1, 30); // 假设处理逻辑需要20s左右,设置了30秒自动过期
    if (result > 0) { // 上锁成功,进入逻辑
        Integer stock = goodsMapper.getStock();
        if (stock > 0) {
            stock =- 1;
            goodsMapper.updateStock(stock);
 
            System.out.println("购买成功!");
        } else {
            System.out.println("没有库存了!");
        }
    }
} catch (Exception e) {
    
} finally {
    jedisUtils.del(key); // 释放锁
}

The above is a relatively complete distributed lock, but there is still a small flaw. It is assumed that a certain request A is processed very slowly. It is expected to take 20s but it takes 35s. When it reaches 30s, the lock expires. Other requests came naturally.

This will not only cause a concurrent execution, but also continue to perform the lock release operation after request A is processed, thus actually handing the lock to the next thread. By analogy, the entire concurrency control will be messed up.

Theoretically, you can set a larger key expiration time, but it is not the best solution. Here comes a concept: locking life.

Lock life extension

As the name suggests, give the lock life extension. The implementation is to extend the lock time when the lock is about to expire. Assume a 30 second lock is used, with a check every 10 seconds to see if the lock still exists. If the lock still exists, keep the lock for 30 seconds. This avoids the possible problem above.

A scheduled task is used here and can be called periodically.

Extension

The value just set for the key is 1. In fact, the request ID can be used to save it, so that you can know which request the lock is from, and you can avoid it when unlocking. Locks on other threads are unlocked. It can be passed by the front end, or generated by the server based on certain rules.

The above is the detailed content of How to use Redis to solve high concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
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.

Redis: Exploring Its Core Functionality and BenefitsRedis: Exploring Its Core Functionality and BenefitsApr 30, 2025 am 12:22 AM

Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

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 Tools

MantisBT

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version