Home  >  Article  >  Backend Development  >  Detailed explanation of redis preventing secondary writing under large concurrency

Detailed explanation of redis preventing secondary writing under large concurrency

小云云
小云云Original
2018-03-28 11:40:101410browse

PHP calls redis to read and write operations. Under large concurrency, it will appear: read key1, and write the content if there is no content. However, under large concurrency, multiple PHP processes will write at the same time. At this time, a lock needs to be added. , that is, the php process that acquires the lock has permission to write.

$lock_key = 'LOCK_PREFIX' . $redis_key;  
$is_lock = $redis->setnx($lock_key, 1); // 加锁  
if($is_lock == true){ // 获取锁权限  
    $redis->setex($redis_key, $expire, $data); // 写入内容  
    // 释放锁  
    $redis->del($lock_key);  
}else{  
    return true; // 获取不到锁权限,直接返回  
}

The idea is: set the key of a lock, setnx is an atomic operation, only one process can write successfully, and return true if the write is successful (indicating that the lock permission is obtained), then write the content and release the lock to delete it. Lock key. Processes that cannot obtain the lock return directly. But there is a situation here. The process that obtains the lock permission reports an error when running after obtaining the lock. As a result, the lock is not released, and the content cannot be written. In this case, the process that does not obtain the lock permission needs to judge the remaining validity time of the lock. , if it is -1, set the effective time of the lock to 5 seconds (5 seconds are reserved for the running time of the process that gets the lock, which is enough). Improved code:

$lock_key = 'LOCK_PREFIX' . $redis_key;  
$is_lock = $redis->setnx($lock_key, 1); // 加锁  
if($is_lock == true){ // 获取锁权限  
    $redis->setex($redis_key, $expire, $data); // 写入内容  
    // 释放锁  
    $redis->del($lock_key);  
}else{  
    // 防止死锁  
    if($redis->ttl($lock_key) == -1){  
        $redis->expire($lock_key, 5);  
    }  
    return true; // 获取不到锁权限,直接返回  
}


The above is the detailed content of Detailed explanation of redis preventing secondary writing under large concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn