How does PHP use redis to prevent secondary writing under large concurrency?

小云云
Release: 2023-03-22 12:32:01
Original
1310 people have browsed it

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.

  1. $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; // 获取不到锁权限,直接返回
    }
    Copy after login

The idea is: set the key of a lock, setnx is an atomic operation, only one process can write successfully, and the write returns true (indicating that the lock is acquired) permission), then write the content and release the lock, which deletes the 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:

  1. $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; // 获取不到锁权限,直接返回
    }
    Copy after login

The above is the detailed content of How does PHP use redis to prevent secondary writing under large concurrency?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template