search
HomeDatabaseRedisTeach you how to correctly use Redis's SETNX to implement the lock mechanism

The following column of Redis Tutorial will introduce to you the correct use of Redis’s SETNX to implement the lock mechanism. I hope it will be helpful to friends in need!

Teach you how to correctly use Redis's SETNX to implement the lock mechanism

setNX is the abbreviation of set if not exists, that is, it is set only when it does not exist. It returns 1 when the setting is successful and 0 when the setting fails. It can be used to achieve the lock effect, but many people have some problems that they do not consider during use.

For example, a certain interface for querying the database adds a cache because of a relatively large number of requests, and sets it to refresh after the cache expires. When the amount of concurrency is relatively large and the cache expires, a large number of concurrent requests will directly query the database, causing an avalanche. The avalanche problem can be avoided if a locking mechanism is used to control only one request to update the cache. The following is a locking method that many people subconsciously think of

$rs = $redis->setNX($key, $value);
if ($rs) {
    //处理更新缓存逻辑
    // ......
    //删除锁
    $redis->del($key);
}

Get the lock through setNX. If successful, update the cache and then delete the lock. In fact, there is a serious problem here: if the cache exits unexpectedly for some reason, the lock will not be deleted and will always exist, so that the cache will never be updated. In order to solve this problem, some people may think of setting an expiration time for the lock, as follows

$redis->multi();
$redis->setNX($key, $value);
$redis->expire($key, $ttl);
$redis->exec();

Because setNX does not have the function of setting the expiration time, it needs to use Expire to set it, and Multi/Exec needs to be used to ensure that the requested Atomicity to prevent setNX from succeeding but failing to Expire. There is still a problem with this: when multiple requests arrive, although only one request's setNX can succeed, any request's Expire can succeed. This means that even if the lock cannot be obtained, the expiration time can be refreshed, causing the lock to remain locked. It's effective, but it still doesn't solve the above problem. Obviously setNX cannot meet the demand. Starting from Redis 2.6.12, SET covers the functions of SETEX. SET itself also includes the function of setting the expiration time, so using SET can solve the problems encountered above.

$rs = $redis->set($key, $value, array('nx', 'ex' => $ttl));
if ($rs) {
    //处理更新缓存逻辑
    // ......
    //删除锁
    $redis->del($key);
}

This step is actually problematic. If a request takes longer to update the cache than the validity period of the lock, causing the lock to become invalid during the cache update process, another request will acquire the lock, but the previous request will When the cache update is completed, if you delete the lock directly, you may accidentally delete the lock created by other requests. So to avoid this problem, you can introduce a random value when creating the lock and judge it when deleting the lock

$rs = $redis->set($key, $random, array('nx', 'ex' => $ttl));
if ($rs) {
     //处理更新缓存逻辑
    // ......
    //先判断随机数,是同一个则删除锁
    if ($redis->get($key) == $random) {
        $redis->del($key);
    }
}

The above is the detailed content of Teach you how to correctly use Redis's SETNX to implement the lock mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
What Are the Performance Trade-offs When Choosing Redis Over a Traditional Database?What Are the Performance Trade-offs When Choosing Redis Over a Traditional Database?May 16, 2025 am 12:01 AM

RedisofferssuperiorspeedfordataoperationsbutrequiressignificantRAMandinvolvestrade-offsindatapersistenceandscalability.1)Itsin-memorynatureprovidesultra-fastread/writeoperations,idealforreal-timeapplications.2)However,largedatasetsmaynecessitatedatae

Redis vs databases: performance comparisonsRedis vs databases: performance comparisonsMay 14, 2025 am 12:11 AM

Redisoutperformstraditionaldatabasesinspeedforread/writeoperationsduetoitsin-memorynature,whiletraditionaldatabasesexcelincomplexqueriesanddataintegrity.1)Redisisidealforreal-timeanalyticsandcaching,offeringphenomenalperformance.2)Traditionaldatabase

When Should I Use Redis Instead of a Traditional Database?When Should I Use Redis Instead of a Traditional Database?May 13, 2025 pm 04:01 PM

UseRedisinsteadofatraditionaldatabasewhenyourapplicationrequiresspeedandreal-timedataprocessing,suchasforcaching,sessionmanagement,orreal-timeanalytics.Redisexcelsin:1)Caching,reducingloadonprimarydatabases;2)Sessionmanagement,simplifyingdatahandling

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.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool